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-07 k3466: #3466 #3474 (#3493)

0xken153a393e7e3449
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.ts
index 682597d83..bdaef2737 100644
--- a/backend/integration/superTabGithub.test.ts
+++ b/backend/integration/superTabGithub.test.ts
@@ -299,7 +299,7 @@ describe('a queued start\'s preparation token', () => {
const conversationId = String((await env.run(tab, { type: 'conversation.create', title: 'Add search', brief: 'Add a search field',
checks: [], ...(requester ? { requesterId: requester.sub } : {}) } as Command)).result.conversationId)
const startId = String((await env.run(tab, { type: 'agent.start', request: { conversationId, machineId, engine: 'codex', name: 'Builder',
- cwd: '/swarm-root/lead', permissionMode: 'full', worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as Command,
+ cwd: '/swarm-root/lead', worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as Command,
contributor)).result.startId)
return { tab, startId }
}
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 39ca7039d..69905813b 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -1113,17 +1113,18 @@ describe('Super Tabs on a real Mongo replica set', () => {
await store.observeMachine(host, tab, 'pool-host', { ...observation })
// Started and assigned in a task: the project chat holds only its coordinator among agents (#2207).
const task = String((await run(tab, { type: 'conversation.create', title: 'Pool work', brief: '', checks: [] })).result.conversationId)
- const request = { permissionMode: 'full', conversationId: task, machineId: 'pool-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,
+ const request = { conversationId: task, machineId: 'pool-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,
requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
await expect(asHost(tab, { type: 'agent.start', request: { ...request, cwd: '/private' } })).rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
- await expect(asHost(tab, { type: 'agent.start', request: { ...request, permissionMode: 'bypassPermissions' } })).rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
+ await expect(asHost(tab, { type: 'agent.start', request: { ...request, permissionMode: 'full' } })).rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
const starts = await Promise.allSettled([asHost(tab, { type: 'agent.start', request }), asHost(tab, { type: 'agent.start', request })])
expect(starts.filter(r => r.status === 'fulfilled')).toHaveLength(1)
expect(starts.filter(r => r.status === 'rejected')).toHaveLength(1)
const startId = (starts.find(r => r.status === 'fulfilled') as PromiseFulfilledResult<Awaited<ReturnType<typeof run>>>).value.result.startId as string
const queued = await store.start(host, tab, startId)
expect(queued.poolGeneration).toBe(generation)
- expect(queued.request.permissionMode).toBe('full')
+ // Swarm v3 (#4215): the agent starts with its owner's own settings.
+ expect(queued.request).not.toHaveProperty('permissionMode')
await expect(run(tab, { type: 'agent.startDispatch', startId })).rejects.toMatchObject({ code: 'HOST_REQUIRED' })
await expect(store.start(peer, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })
const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'pool-host')
@@ -1166,7 +1167,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
expect((await pool()).observation.quotaReasons).toEqual({ codex: 'OpenAI could not be reached.' })
// Started in a task: the project chat holds only its coordinator among agents (#2207).
const task = String((await run(tab, { type: 'conversation.create', title: 'Health work', brief: '', checks: [] })).result.conversationId)
- const request = { permissionMode: 'full', conversationId: task, machineId: 'health-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,
+ const request = { conversationId: task, machineId: 'health-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,
requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'health-host')
// Preparation failures remain failed starts, but do not disable either engine.
diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.ts
index 914dd82ec..e6f1fb669 100644
--- a/backend/src/superTabs/machines.test.ts
+++ b/backend/src/superTabs/machines.test.ts
@@ -97,17 +97,14 @@ function refusal(state: SuperTabState, request: AgentStartRequest, start?: Agent
const refused = (error: SuperTabError) => error.message.split('Refused: ')[1] ?? ''
describe('a start on a contributed machine', () => {
- it.each(['claude', 'codex'])('admits full permissions for %s, including dispatch rechecks', engine => {
- const f = setup()
- expect(refusal(f.state, f.request({ engine, permissionMode: 'full' }))).toBeNull()
- expect(refusal(f.state, f.request({ engine, permissionMode: 'full' }), { poolGeneration: 'g1' } as AgentStart)).toBeNull()
- })
-
- it.each(['ask', 'auto', 'readOnly', 'bypass'])('refuses permission mode %s with an accurate explanation', permissionMode => {
+ // Swarm v3 (task #4215): every agent starts with its owner's own settings. A CLI from before full mode answers these exact
+ // words by sending the start again without the field, so CLIs from the last 30 days keep starting agents.
+ it.each(['full', 'ask', 'auto', 'readOnly', 'bypass'])('refuses permission mode %s in the words older CLIs retry without it', permissionMode => {
const f = setup()
const error = refusal(f.state, f.request({ permissionMode }))!
expect(error).toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
- expect(error.message).toContain('permissionMode (only full is accepted; leave it out to use the machine’s default)')
+ expect(error.message.endsWith('Refused: permissionMode (it runs with its own default account settings, so leave it out).')).toBe(true)
+ expect(error.message).not.toContain('full permissions')
})
it('is admitted inside the contribution: its project folder, one of its engines, no account settings', () => {
@@ -171,7 +168,7 @@ describe('a start on a contributed machine', () => {
const error = refusal(f.state, f.request({ cwd: '/elsewhere', engine: 'opencode', codexHome: '/h', permissionMode: 'bypass' }))!
expect(error.message).toContain('cwd (this project uses /data/swarm-projects/tab/lead on it)')
expect(error.message).toContain('engine (it contributes claude, codex)')
- expect(error.message).toContain('codexHome (it runs with its own default account settings, so leave it out); permissionMode (only full is accepted')
+ expect(error.message).toContain('codexHome (it runs with its own default account settings, so leave it out); permissionMode (it runs with its own default account settings, so leave it out).')
})
it('says nothing of other projects or machines', () => {
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 4a10128de..b73f2af4a 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -864,11 +864,11 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
const local = localModelAllowed(state, request, now)
const settings = (['codexHome', 'gridModel', 'gridName'] as const).filter(key => request[key] && !(local && key !== 'codexHome'))
if (settings.length) refused.push(`${settings.join(', ')} (it runs with its own default account settings, so leave ${settings.length > 1 ? 'them' : 'it'} out)`)
- if (request.permissionMode !== undefined && request.permissionMode !== 'full') {
- refused.push('permissionMode (only full is accepted; leave it out to use the machine’s default)')
- }
+ // Swarm v3 (task #4215): an agent starts with its owner's own permission settings, so a start names no mode. Last, in the
+ // words a CLI from before full mode answers by sending the start again without it (cli superTabs/start.ts before #4215).
+ if (request.permissionMode !== undefined) refused.push('permissionMode (it runs with its own default account settings, so leave it out)')
if (refused.length) {
- fail('OUTSIDE_CONTRIBUTION', `${pool.name} accepts only its contributed project folder, engines and default account settings, with full permissions for Swarm agents. Refused: ${refused.join('; ')}.`, 403)
+ fail('OUTSIDE_CONTRIBUTION', `${pool.name} accepts only its contributed project folder, engines and default account settings. Refused: ${refused.join('; ')}.`, 403)
}
// A Buddy-only machine is recorded with its Buddy's start, before its host ever read the Swarm: the start waits for it.
if (machineOffline(pool, now) && !(pool.buddyOnly && !pool.observation)) fail('MACHINE_OFFLINE', 'Wait for a fresh reading from the contributed machine.')
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 281633904..341555cd6 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -220,10 +220,8 @@ Machine:
harness flash [flags] re-flash a plugged-in circle device over USB. Flags go straight to the
flasher: --detect-only, --port, --version, --yes, --erase-nvs
-Team account (the separate "harnessteam" user that runs Swarm work on this computer):
- harness team setup make the account, its daemon and its engines, so teammates' agents cannot read
- your files; run again to repair (--sign-in-again: a new sign-in)
- harness team status whether it exists and runs, its sign-in, privacy check and engines
+Team account (the separate "harnessteam" user made for Swarm work before Swarm v3, which has none):
+ harness team status whether it is still there, its daemon (which stops once no agent runs), and how to delete it
harness team on | off a computer used only for agents runs Swarm work only (on), or signs back in as
your own computer (off)
harness team remove delete the account, its home folder and its daemon
@@ -3124,7 +3122,7 @@ switch (cmd) {
if (rest[0] === 'ps') {
usableMachines().then(async (machines) => {
const team = machines.find((machine) => machine.label.endsWith('· Team'))
- if (!team) { console.error('No Harness Team account on this account yet: harness team setup makes one.'); return 1 }
+ if (!team) { console.error('No Harness Team account on this account.'); return 1 }
return psCommand(['--machine', team.label, '--all', ...rest.slice(1)], { machines: async () => machines })
}).then((code) => { process.exitCode = code }).catch(onError)
break
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index dcf7e6d4e..476505ba3 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -77,10 +77,9 @@ vi.mock('../../engines/kit/nativeHookFiles.js', () => ({
const trust = vi.hoisted(() => ({
claudeTrusts: vi.fn((_path: string) => false), codexTrusts: vi.fn((_path: string, _profile?: string | null) => false),
preTrustClaudeProject: vi.fn((_path: string): unknown => undefined), preTrustCodexProject: vi.fn((_path: string, _profile?: string | null): unknown => undefined),
- acceptFullMode: vi.fn((_engine: string, _environment?: NodeJS.ProcessEnv): unknown => 'accepted'),
}))
-const { preTrustClaudeProject, preTrustCodexProject, acceptFullMode } = trust
-vi.mock('../../engines/launchPrep.js', () => ({ acceptFullMode: trust.acceptFullMode, folderTrust: (engine: string, profile?: string | null) => engine === 'claude'
+const { preTrustClaudeProject, preTrustCodexProject } = trust
+vi.mock('../../engines/launchPrep.js', () => ({ folderTrust: (engine: string, profile?: string | null) => engine === 'claude'
? { trusts: (path: string) => trust.claudeTrusts(path), record: (path: string) => trust.preTrustClaudeProject(path) }
: engine === 'codex' ? { trusts: (path: string) => trust.codexTrusts(path, profile), record: (path: string) => trust.preTrustCodexProject(path, profile) } : null }))
// The connections an agent on a profile home is given (lib/connectors/agents.ts): never written into a real folder here.
@@ -236,22 +235,20 @@ describe('creating an agent', () => {
expect(place.swarmInstructions!.startsWith('Use the built-in swarm-tools skill')).toBe(true)
})
- // A Swarm Lead on the Mac Studio sat at Claude Code's "Yes, I accept" for full mode before its first turn (2026-10-26).
- it('accepts full mode\'s warning for a Swarm agent the Swarm starts in full mode, and for nothing else', async () => {
- await setup().create(request({ swarmRole: 'coordinator', permissionMode: 'full' }))
- expect(acceptFullMode).toHaveBeenLastCalledWith('claude', undefined)
- const launch = { current: () => true, environment: { HOME: root, CLAUDE_CONFIG_DIR: '/moved' }, prepareHooks: async () => true } as unknown as NativeLaunch
- await setup({ native: async () => ({ ok: true, launch }) }).create(request({ swarmRole: 'agent', permissionMode: 'full' }))
- expect(acceptFullMode).toHaveBeenLastCalledWith('claude', expect.objectContaining({ CLAUDE_CONFIG_DIR: '/moved' }))
- await setup().create(request({ swarmRole: 'coordinator', permissionMode: 'auto' }))
- await setup().create(request({ permissionMode: 'full' }))
- expect(acceptFullMode).toHaveBeenCalledTimes(2)
- // A settings file it cannot write leaves the engine to ask, and the launch goes on.
- vi.mocked(acceptFullMode).mockImplementationOnce(() => { throw new Error('settings locked') }).mockImplementationOnce(() => { throw 'worse' })
- expect(await setup().create(request({ swarmRole: 'coordinator', permissionMode: 'full' }))).toMatchObject({ ok: true })
- expect(await setup().create(request({ swarmRole: 'coordinator', permissionMode: 'full' }))).toMatchObject({ ok: true })
- expect(console.warn).toHaveBeenCalledWith('[agent] full mode acceptance · settings locked')
- expect(console.warn).toHaveBeenCalledWith('[agent] full mode acceptance · worse')
+ // Swarm v3 (task #4215): a Swarm agent starts with its owner's own settings. Harness wrote full mode's warning acceptance
+ // into them for every Swarm agent in full mode (2026-10-26); a person who chooses full mode answers Claude Code's own warning.
+ it('writes nothing into the person\'s settings for a Swarm agent, with no mode or in full mode', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'own-settings-')), config = join(home, 'claude'), settings = join(config, 'settings.json')
+ mkdirSync(config); writeFileSync(settings, '{"theme":"dark"}\n')
+ const launch = { current: () => true, environment: { HOME: home, CLAUDE_CONFIG_DIR: config }, prepareHooks: async () => true } as unknown as NativeLaunch
+ try {
+ for (const over of [{}, { permissionMode: 'full', bypassPermission: true }]) {
+ for (const swarmRole of ['coordinator', 'agent']) {
+ expect(await setup({ native: async () => ({ ok: true, launch }) }).create(request({ swarmRole, ...over }))).toMatchObject({ ok: true })
+ }
+ }
+ expect(readFileSync(settings, 'utf8')).toBe('{"theme":"dark"}\n')
+ } finally { rmSync(home, { recursive: true, force: true }) }
})
// Audit M1: beside a Team account, the owner's agents get a private temporary folder, and the launch's own variables win.
@@ -339,12 +336,10 @@ describe('creating an agent', () => {
// HARNESS_SWARM=off: the core holds none of the Swarm's launch code, so a start that asks for a Swarm role is
// refused before anything is written or launched, and every other start is as it was.
it('refuses a Swarm role while the Swarm is off, before opening a pane, and starts everything else as before', async () => {
- acceptFullMode.mockClear()
const off = setup({ swarmLaunch: undefined })
expect(await off.create(request({ cwd: folder(), swarmRole: 'agent' })))
.toEqual({ ok: false, error: 'SWARM_SKILL_FAILED', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' })
expect(createAndRegisterPane).not.toHaveBeenCalled()
- expect(acceptFullMode).not.toHaveBeenCalled()
expect(await off.create(request({ cwd: folder() }))).toMatchObject({ ok: true })
expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0]).not.toHaveProperty('swarmSkill')
})
@@ -408,7 +403,8 @@ describe('creating an agent', () => {
// 2026-10-30: a Cmd+S Swarm's PM, in a clone or worktree the desktop made and sent as a plain cwd, sat at Claude Code's
// trust question, which no Swarm view shows.
- it('trusts a local Claude Swarm agent in full mode in a clone in the projects root or a worktree Harness made', async () => {
+ // Its owner's own mode since task #4215: the trust follows the Swarm's checkout, not full mode.
+ it('trusts a local Claude Swarm agent in any mode in a clone in the projects root or a worktree Harness made', async () => {
vi.mocked(projectsRoot).mockReturnValue(root)
try {
const clone = folder(), plain = folder(['README.md']), worktree = join(folder(), 'worktree')
@@ -417,19 +413,20 @@ describe('creating an agent', () => {
vi.mocked(harnessMadeWorktree).mockImplementation(async path => path === worktree)
const authority = { id: 'fixture', label: 'harness-claude-fixture', current: () => true, hold: () => {} }
const prepare = (over: Record<string, unknown>, local = true) =>
- setup().create.prepare(request({ swarmRole: 'coordinator', permissionMode: 'full', bypassPermission: true, ...over }), authority, { local })
+ setup().create.prepare(request({ swarmRole: 'coordinator', ...over }), authority, { local })
expect((await prepare({ cwd: clone })).ok).toBe(true)
expect(preTrustClaudeProject).toHaveBeenCalledWith(clone)
- await prepare({ cwd: worktree })
+ await prepare({ cwd: worktree, permissionMode: 'full', bypassPermission: true })
expect(preTrustClaudeProject).toHaveBeenLastCalledWith(worktree)
expect(harnessMadeWorktree).toHaveBeenCalledWith(worktree, root)
- // Not the person's own folder, not relayed, not outside a Swarm or full mode, not for Codex.
+ await prepare({ cwd: clone, permissionMode: 'ask' })
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(3)
+ // Not the person's own folder, not relayed, not outside a Swarm, not for Codex.
await prepare({ cwd: plain })
await prepare({ cwd: clone }, false)
- await prepare({ cwd: clone, swarmRole: null })
- await prepare({ cwd: clone, permissionMode: 'auto', bypassPermission: false })
+ await prepare({ cwd: clone, swarmRole: null, permissionMode: 'full', bypassPermission: true })
await prepare({ cwd: clone, engine: 'codex' })
- expect(preTrustClaudeProject).toHaveBeenCalledTimes(2)
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(3)
expect(preTrustCodexProject).not.toHaveBeenCalled()
} finally {
vi.mocked(projectsRoot).mockReset()
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index d6ac1a1d0..6777625ad 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -43,7 +43,7 @@ import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPrepara
import type { publishGridConfigDir } from '../../lib/publishedGridConfig.js'
import { nativeHookLocations } from '../../engines/kit/nativeLocations.js'
import { engineHooks } from '../../engines/hooks.js'
-import { acceptFullMode, folderTrust } from '../../engines/launchPrep.js'
+import { folderTrust } from '../../engines/launchPrep.js'
import { projectsRoot } from '../../lib/projectFolder.js'
import { harnessMadeWorktree } from '../../lib/gitProject.js'
import { NativeFiles } from '../../engines/kit/nativeFiles.js'
@@ -144,12 +144,13 @@ export function createAgentCreator({
// A Swarm agent's folder has content: the desktop's New Swarm clones a GitHub project into the projects root, or makes
// a worktree of a local repository, itself, and sends the folder as a plain cwd. 2026-10-30: a Cmd+S Swarm's PM sat
// at Claude Code's "do you trust this folder?", which no Swarm view shows; it read Idle and every message to it was
- // withheld. The person chose that repository and full mode for the Swarm in this window, so a Claude Code Swarm agent
- // in full mode is trusted in a Git checkout directly in the projects root or a worktree Harness made, read from disk.
+ // withheld. The person chose that repository for the Swarm in this window, so a Claude Code Swarm agent, in whatever mode
+ // its owner's settings give (task #4215), is trusted in a Git checkout directly in the projects root or a worktree Harness
+ // made, read from disk.
// Never from a relayed request, which could name any repository here. Codex's trust also sets defaults for the
// person's own sessions in that folder, so it stays theirs to give.
const trustSwarmFolder = !trustEmptyProject && context?.local === true && !dsh && engine === 'claude' && !!input.swarmRole
- && (permissionMode === 'full' || permissionMode === 'teamWritten') && await swarmFolder(cwd)
+ && await swarmFolder(cwd)
if (!authority.current()) return stale()
// A harness can pin its permission mode (`dshPinnedPermissionMode`): the Grid harness starts model
// servers, which Codex's sandbox would start without a GPU. Pinned before anything reads the mode,
@@ -308,13 +309,6 @@ export function createAgentCreator({
console.log(describeGridLaunch(engine, grid, built.launch.webSearch))
}
if (!current()) return stale()
- // The Swarm starts its agents in full mode, so a machine that never accepted full mode's warning stops each one there
- // before its first turn (Claude Code's "Yes, I accept", the Mac Studio, 2026-10-26). The Swarm's owner chose that mode
- // for it; recorded the way the engine records the person's own yes, in the home this launch reads.
- if (input.swarmRole && (permissionMode === 'full' || permissionMode === 'teamWritten')) {
- try { acceptFullMode(engine, native ? { ...native.environment, ...gridLaunch?.env, ...dshEnv } : undefined) }
- catch (error) { console.warn(`[agent] full mode acceptance · ${error instanceof Error ? error.message : error}`) }
- }
if (trustEmptyProject || trustSwarmFolder) {
try {
// A clone or user edit can arrive while dependencies are being prepared.
diff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.ts
index a30790fe8..352eb32cd 100644
--- a/cli/src/core/agents/discovery.spec.ts
+++ b/cli/src/core/agents/discovery.spec.ts
@@ -139,6 +139,16 @@ describe('discovery', () => {
expect(mode, 'this fixture must name a mode').not.toBeNull()
})
+ // Swarm v3 (task #4215): a Swarm agent's mode is the one its person chose, or none. An agent Harness once started in
+ // full mode still runs with that flag until it relaunches; read back, the relaunch would skip permissions again.
+ it('never reads a Swarm agent\'s permissions off its process', async () => {
+ const run = setup()
+ const swarm = row({ swarmSkill: { role: 'coordinator', key: 'swarm-lead' } } as Partial<RegisteredSession>)
+ await run.handlers.onObserved(seen({ args: 'claude --dangerously-skip-permissions' } as Partial<DiscoveredTerminalAgent>), swarm)
+ expect(run.deps.registry.setPermissionMode).not.toHaveBeenCalled()
+ expect(run.deps.registry.setBypassPermission).not.toHaveBeenCalled()
+ })
+
it('reads a Buddy launched in full mode back as full, never as an older Buddy\'s mode (task #2832)', () => {
expect(permissionModeFromArgv('codex', 'codex --dangerously-bypass-approvals-and-sandbox -c tui.fullscreen_transcript=false')).toBe('full')
expect(permissionModeFromArgv('claude', 'claude --dangerously-skip-permissions')).toBe('full')
diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.ts
index b4883080f..bcbb955bb 100644
--- a/cli/src/core/agents/discovery.ts
+++ b/cli/src/core/agents/discovery.ts
@@ -113,12 +113,15 @@ export function createDiscoveryHandlers({
// that did not yet) learns it here, before any pane recreation ever needs it.
// `observed.engine`, not `current.engine`: for a terminal that just adopted one, the row's
// engine was `terminal` a line ago, which has no bypass flag and would read every launch as "no".
- registry.setBypassPermission(current.agentId, bypassPermissionActive(observed.engine, observed.args))
+ // Not a Swarm agent's (task #4215): its mode is the one its person chose, or none. One Harness started in full mode
+ // before then still runs with that flag until it relaunches, and read back the relaunch would skip permissions again.
+ const own = !current.swarmSkill
+ if (own) registry.setBypassPermission(current.agentId, bypassPermissionActive(observed.engine, observed.args))
// And the exact MODE, fill-only: a row that recorded one at create is authoritative, and one
// that never did (adopted from a terminal, written by an older build, created by a path that
// passes no mode) learns it from the same argv — so its restart brings back
// `--dangerously-skip-permissions`, not the auto mode `bypassPermission` alone would pick.
- if (!current.permissionMode) {
+ if (own && !current.permissionMode) {
const mode = permissionModeFromArgv(observed.engine, observed.args)
if (mode) registry.setPermissionMode(current.agentId, mode)
}
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 57d0bae24..f2a31578b 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -898,42 +898,43 @@ describe('agent_create with a receipt', () => {
// WIN-DELL and the Mac Studio, 2026-10-26: Swarm Leads in a reused or fresh checkout of the project's repository sat at
// Claude Code's trust question, and so did the next Lead in a worktree of it, its source never answered.
- it('trusts a Swarm agent\'s checkout of its remote project in the Swarm\'s full mode, and no other existing folder', async () => {
+ it('trusts a Swarm agent\'s checkout of its remote project in its owner\'s own mode, and no other existing folder', async () => {
const { ask, replies } = setup()
const launch = async (payload: Record<string, unknown>, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }); await vi.waitFor(() => expect(replies).toHaveLength(n)) }
const remote = { projectSource: 'remote', repositoryUrl: 'https://github.com/acme/app.git' }
- await launch({ engine: 'claude', ...remote, swarmRole: 'lead', permissionMode: 'full' }, 1)
+ await launch({ engine: 'claude', ...remote, swarmRole: 'lead' }, 1)
expect(preTrustClaudeProject).toHaveBeenCalledWith('/projects/prepared')
- // The guard: the same checkout outside a Swarm or outside full mode, and a Swarm agent in a folder it was handed.
+ // The guard: the same checkout outside a Swarm, and a Swarm agent in a folder it was handed.
await launch({ engine: 'claude', ...remote, permissionMode: 'full' }, 2)
- await launch({ engine: 'claude', ...remote, swarmRole: 'lead', permissionMode: 'auto' }, 3)
+ await launch({ engine: 'claude', cwd: dir, swarmRole: 'lead' }, 3)
await launch({ engine: 'claude', cwd: dir, swarmRole: 'lead', permissionMode: 'full' }, 4)
- await ask({ creationId: `${CREATION}-5`, engine: 'claude', projectSource: 'worktree', gitSource: '/elsewhere', branchName: 'feature', swarmRole: 'lead', permissionMode: 'full' }, false)
+ await ask({ creationId: `${CREATION}-5`, engine: 'claude', projectSource: 'worktree', gitSource: '/elsewhere', branchName: 'feature', swarmRole: 'lead' }, false)
await vi.waitFor(() => expect(replies).toHaveLength(5))
expect(preTrustClaudeProject).toHaveBeenCalledOnce()
// Claude Code only: a Codex Lead's checkout is not trusted for it.
- await launch({ engine: 'codex', ...remote, swarmRole: 'lead', permissionMode: 'full' }, 6)
+ await launch({ engine: 'codex', ...remote, swarmRole: 'lead' }, 6)
expect(preTrustCodexProject).not.toHaveBeenCalled()
// A worktree made from that checkout then inherits its answer.
vi.mocked(claudeTrusts).mockImplementation(path => path === '/projects/prepared')
- await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/projects/prepared', branchName: 'feature', swarmRole: 'lead', permissionMode: 'full' }, 7)
+ await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/projects/prepared', branchName: 'feature', swarmRole: 'lead' }, 7)
expect(preTrustClaudeProject).toHaveBeenCalledTimes(2)
})
// 2026-10-30: a new Swarm made with Cmd+S on a local openharness checkout started its PM in a worktree of that
// checkout, which Claude Code had never been told to trust; the PM sat at the question, shown as Idle in the Swarm.
- it('trusts the worktree of a repository the person picked in this machine\'s window for a Swarm agent in full mode', async () => {
+ it('trusts the worktree of a repository the person picked in this machine\'s window for a Swarm agent in any mode', async () => {
const { ask, replies } = setup()
const launch = async (payload: Record<string, unknown>, local: boolean, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }, local); await vi.waitFor(() => expect(replies).toHaveLength(n)) }
const worktree = { projectSource: 'worktree', gitSource: '/Users/me/openharness', branchName: 'lively-meteor' }
- await launch({ engine: 'claude', ...worktree, swarmRole: 'lead', permissionMode: 'full' }, true, 1)
+ await launch({ engine: 'claude', ...worktree, swarmRole: 'lead' }, true, 1)
expect(preTrustClaudeProject).toHaveBeenCalledWith('/projects/prepared')
- // Not relayed, not outside a Swarm or full mode, not for Codex: those stay the person's question.
- await launch({ engine: 'claude', ...worktree, swarmRole: 'lead', permissionMode: 'full' }, false, 2)
- await launch({ engine: 'claude', ...worktree, permissionMode: 'full' }, true, 3)
- await launch({ engine: 'claude', ...worktree, swarmRole: 'lead', permissionMode: 'auto' }, true, 4)
- await launch({ engine: 'codex', ...worktree, swarmRole: 'lead', permissionMode: 'full' }, true, 5)
- expect(preTrustClaudeProject).toHaveBeenCalledOnce()
+ await launch({ engine: 'claude', ...worktree, swarmRole: 'lead', permissionMode: 'full' }, true, 2)
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(2)
+ // Not relayed, not outside a Swarm, not for Codex: those stay the person's question.
+ await launch({ engine: 'claude', ...worktree, swarmRole: 'lead' }, false, 3)
+ await launch({ engine: 'claude', ...worktree, permissionMode: 'full' }, true, 4)
+ await launch({ engine: 'codex', ...worktree, swarmRole: 'lead' }, true, 5)
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(2)
expect(preTrustCodexProject).not.toHaveBeenCalled()
})
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 11ce573f1..9044e6b87 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -138,20 +138,20 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// the person's own repo is theirs to answer for (engines/kit/folderTrust.ts); a worktree gets only
// the answer its source repo already has. `branch` IS the source folder: nothing to record.
//
- // One consented exception: a Swarm agent in the Swarm's full mode, in the checkout a remote project resolved
+ // One consented exception: a Swarm agent, in any mode (task #4215), in the checkout a remote project resolved
// to (cloned now, or one already there that holds that very repository). The person chose this repository
- // and full mode for the Swarm, and machine trust favors that choice over a prompt. 2026-10-26: on WIN-DELL
+ // for the Swarm, and machine trust favors that choice over a prompt. 2026-10-26: on WIN-DELL
// a Lead in a reused `harnesses\openharness` sat at Claude Code's trust question; on the Mac Studio a Lead in
// a fresh clone did, and the next Lead, in a worktree of it, asked again because the source had never been
// answered. Its Yes then landed under the source's key (Claude Code records a worktree's answer under its
// main repository), which made the source look trusted before the worktree started.
// Claude Code only: Codex's trust also sets its defaults for the person's own later sessions in that folder.
//
- // And a worktree of a repository the person picked in this machine's OWN window for a Swarm agent in full mode:
+ // And a worktree of a repository the person picked in this machine's OWN window for a Swarm agent, in any mode (#4215):
// 2026-10-30, a new Swarm made with Cmd+S on a local openharness checkout started its PM in a worktree of it, and
// the PM sat at Claude Code's trust question, which no Swarm view shows; it read Idle and every message to it was
// withheld. Only from a local frame: a relayed request could name any repository on this machine.
- const swarmAgent = input.engine === 'claude' && !!input.swarmRole && (input.permissionMode === 'full' || input.permissionMode === 'teamWritten')
+ const swarmAgent = input.engine === 'claude' && !!input.swarmRole
const swarmCheckout = swarmAgent && (projectFolder.source === 'remote' || (projectFolder.source === 'worktree' && local))
try {
// A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index cdc14fd86..9b40ffd77 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -149,6 +149,7 @@ import { readerEngine, READER_SERVICES } from '../engines/worker/protocol.js'
import { createRecaps } from './turns/recaps.js'
import { summaryReader } from './turns/summaries.js'
import { stopDeadline } from './stopDeadline.js'
+import { stopsForGood } from './stopReasons.js'
import { createUpdateHandoff, handOverOnceReleased, probeStagedMaster, type TeardownStep } from './updateHandoff.js'
import { needsUpdaterBeside, startUpdaterBeside } from './updaterBeside.js'
import { createHeartbeats } from './turns/heartbeats.js'
@@ -1964,6 +1965,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const slowProbeMs = Number(harnessd.HARNESSD_TEST_SLOW_PROBE_MS) || 0
const gridAssignments = createGridAssignments({ models: () => ports.models ?? MODELS_OFF, registry,
revision: (id) => restartJobs.revision(id), announce: announceSession })
+ // Set once the stop below exists: a Harness Team account's daemon stops for good once no agent runs in it.
+ let afterAgentsPass = (): void => {}
const agentReconciler = new TerminalAgentReconciler({
// The hook server starts before restore. Its early SessionStart hints must not run a full
// discovery scan over rows whose panes have not been recreated yet (and archive those rows).
@@ -1982,6 +1985,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
...discovery,
onReconciled: (agents) => {
gridAssignments.observe(agents)
+ afterAgentsPass()
if (ptyDrain) {
void ptyDrain.step().catch((error) => {
console.error('[terminal] ptyhost: drain failed:', error instanceof Error ? error.message : error)
@@ -3156,7 +3160,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
/** Stopping for good — removed from the account, or connected from elsewhere: tell harnessd's master,
* which restarts any other exit (harnessd/protocol.ts). */
- const forGood = (reason: string): boolean => reason === 'revoked' || reason === 'busy'
const shutdown = async (signal: string): Promise<void> => {
heldLaunches.close()
installedHooks?.close()
@@ -3167,7 +3170,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
registry.flush({ exiting: true })
const leave = (): never => {
try { if (readPid() === process.pid) rmSync(PID_FILE, { force: true }) } catch { /* ignore */ }
- process.exit(coreLink.supervised && forGood(signal) ? CORE_EXIT_STOP : 0)
+ process.exit(coreLink.supervised && stopsForGood(signal) ? CORE_EXIT_STOP : 0)
}
// A core with no master keeps the master's grace on itself (core/stopDeadline.ts).
const deadline = stopDeadline({ supervised: coreLink.supervised, exit: leave, log: (line) => console.log(line) })
@@ -3221,6 +3224,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
daemonBoot.stopHere = (why) => void shutdown(why)
process.on('SIGINT', () => void shutdown('SIGINT'))
process.on('SIGTERM', () => void shutdown('SIGTERM'))
+ // Swarm v3 has no Team accounts: a Team account's daemon stops for good after a pass finds no agent running in it, an
+ // engine or a pane (superTabs/inCore/teamRetire.ts).
+ if (swarm) {
+ afterAgentsPass = swarm.teamRetirement({ teamAccount: swarm.isTeamAccount(), log: (line) => console.log(line),
+ live: () => registry.list().filter((session) => session.active || registry.terminalAvailable(session.agentId)).length,
+ stop: (reason) => void shutdown(reason) })
+ }
// A core whose master is gone stops, so nothing is left holding the port for a master that is not
// there to restart it.
coreLink.onMasterGone(() => void shutdown('the harnessd master is gone'))
diff --git a/cli/src/core/stopReasons.spec.ts b/cli/src/core/stopReasons.spec.ts
new file mode 100644
index 000000000..3aacf75ff
--- /dev/null
+++ b/cli/src/core/stopReasons.spec.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest'
+import { stopsForGood } from './stopReasons.js'
+
+describe('a core stop that keeps the daemon stopped (the master exits and launchd, systemd or Windows leave it)', () => {
+ it('is a revoked sign-in, a computer in use elsewhere, or a retired Team account\'s daemon (#4221)', () => {
+ expect(['revoked', 'busy', 'retired'].map(stopsForGood)).toEqual([true, true, true])
+ })
+
+ it('is no other stop: a signal or the master asking', () => {
+ expect(['SIGTERM', 'the harnessd master asked this core to stop'].map(stopsForGood)).toEqual([false, false])
+ })
+})
diff --git a/cli/src/core/stopReasons.ts b/cli/src/core/stopReasons.ts
new file mode 100644
index 000000000..867bf7c4a
--- /dev/null
+++ b/cli/src/core/stopReasons.ts
@@ -0,0 +1,6 @@
+/** The core stops that keep the daemon stopped: the master exits after them, and launchd, systemd and Windows leave a
+ * clean exit stopped. A revoked sign-in, a computer in use elsewhere, and a Harness Team account's daemon with no agent
+ * left in it (superTabs/inCore/teamRetire.ts). */
+const FOR_GOOD = new Set(['revoked', 'busy', 'retired'])
+
+export const stopsForGood = (reason: string): boolean => FOR_GOOD.has(reason)
diff --git a/cli/src/engines/__fixtures__/launch-argv.golden.json b/cli/src/engines/__fixtures__/launch-argv.golden.json
index b8a4a185a..8a7d2bd0f 100644
--- a/cli/src/engines/__fixtures__/launch-argv.golden.json
+++ b/cli/src/engines/__fixtures__/launch-argv.golden.json
@@ -732,7 +732,6 @@
"claude · new, mode plan · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","plan"],"script":"7b9a7551f122ab5c","command":3},
"claude · new, mode ask · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","default"],"script":"7b9a7551f122ab5c","command":3},
"claude · new, mode full · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions"],"script":"7b9a7551f122ab5c","command":2},
- "claude · new, mode buddy · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions"],"script":"7b9a7551f122ab5c","command":2},
"claude · new, mode teamWritten · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions","--setting-sources","user","--strict-mcp-config"],"script":"7b9a7551f122ab5c","command":5},
"claude · first prompt · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"7b9a7551f122ab5c","command":2},
"claude · resume · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--resume","sess-0001"],"script":"7b9a7551f122ab5c","command":3},
@@ -761,7 +760,6 @@
"codex · new, mode readOnly · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--sandbox","read-only","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":5},
"codex · new, mode ask · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":3},
"codex · new, mode full · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":4},
- "codex · new, mode readOnlyAsk · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":4},
"codex · new, mode teamWritten · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":4},
"codex · first prompt · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"533ec1354e8b74a3","command":4},
"codex · resume · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","resume","sess-0001","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":5},
@@ -967,7 +965,6 @@
"claude · new, mode plan · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","plan"],"script":"6d299a48b039bf1e","command":3},
"claude · new, mode ask · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","default"],"script":"6d299a48b039bf1e","command":3},
"claude · new, mode full · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions"],"script":"6d299a48b039bf1e","command":2},
- "claude · new, mode buddy · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions"],"script":"6d299a48b039bf1e","command":2},
"claude · new, mode teamWritten · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions","--setting-sources","user","--strict-mcp-config"],"script":"6d299a48b039bf1e","command":5},
"claude · first prompt · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"6d299a48b039bf1e","command":2},
"claude · resume · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--resume","sess-0001"],"script":"6d299a48b039bf1e","command":3},
@@ -1075,7 +1072,6 @@
"codex · new, mode readOnly · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--sandbox","read-only","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":5},
"codex · new, mode ask · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":3},
"codex · new, mode full · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":4},
- "codex · new, mode readOnlyAsk · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":4},
"codex · new, mode teamWritten · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":4},
"codex · first prompt · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"585ef6d2032354bb","command":4},
"codex · resume · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","resume","sess-0001","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":5},
diff --git a/cli/src/engines/claude/launch.ts b/cli/src/engines/claude/launch.ts
index afb9a5764..e03bf5297 100644
--- a/cli/src/engines/claude/launch.ts
+++ b/cli/src/engines/claude/launch.ts
@@ -10,10 +10,6 @@ const permissionModes = {
plan: ['--permission-mode', 'plan'],
ask: ['--permission-mode', 'default'],
full: ['--dangerously-skip-permissions'],
- // An older Buddy's saved mode, from when a guard held it read-only. A Buddy is its owner's right hand now (Ken, 11-04, task
- // #2832): relaunched like their own session, in full mode. After `full`, so a process's argv reads back as `full`
- // (lib/processTable.ts). Remove after 2026-12-04, once every Buddy saved before #2832 has started again.
- buddy: ['--dangerously-skip-permissions'],
// Code a Harness Team agent wrote, in a Team account (backend superTabs/teamWritten.ts, audit H2): full mode, and nothing the
// branch carries. `user` and not `local`: a branch can commit `.claude/settings.local.json`. Harness's hooks are in the user
// settings. Claude Code 2.1.316, tried: planted settings.json, settings.local.json and .mcp.json each ran in a trusted
@@ -47,14 +43,6 @@ export const launch: EngineLaunch = {
home: { variable: 'CLAUDE_CONFIG_DIR', otherwise: 'home' }, file: '.claude.json',
format: 'json', projects: 'projects', accepted: 'hasTrustDialogAccepted', entry: { allowedTools: [] },
},
- /**
- * "WARNING: Claude Code running in Bypass Permissions mode … Yes, I accept", the first time `--dangerously-skip-permissions`
- * runs: a Swarm Lead on the Mac Studio sat there before its first turn (2026-10-26). Accepting writes
- * `skipDangerousModePermissionPrompt: true` to the user settings, "Whether the user has accepted the bypass permissions
- * mode dialog" in its settings schema, and the key its own message tells people to add (2.1.310; with it set the
- * dialog is not shown, tried with the binary).
- */
- bypassAcceptance: { home: { variable: 'CLAUDE_CONFIG_DIR', otherwise: { folder: '.claude' } }, file: 'settings.json', key: 'skipDangerousModePermissionPrompt' },
/**
* `.mcp.json` in a folder above, such as the home's, is asked about as "New MCP server found in this project". Its
* default, "Continue without using this MCP server", adds the name to `disabledMcpjsonServers` in the folder's
diff --git a/cli/src/engines/codex/launch.ts b/cli/src/engines/codex/launch.ts
index 7024abad2..802aac4f3 100644
--- a/cli/src/engines/codex/launch.ts
+++ b/cli/src/engines/codex/launch.ts
@@ -5,10 +5,6 @@ const permissionModes = {
readOnly: ['--sandbox', 'read-only'],
ask: [],
full: ['--dangerously-bypass-approvals-and-sandbox'],
- // An older Codex Buddy's saved mode, from when it read in a read-only sandbox. A Buddy is its owner's right hand now (Ken,
- // 11-04, task #2832): relaunched with full access, as their own session. After `full`, so argv reads back as `full`.
- // Remove after 2026-12-04, once every Buddy saved before #2832 has started again.
- readOnlyAsk: ['--dangerously-bypass-approvals-and-sandbox'],
// Code a Harness Team agent wrote, in a Team account (backend superTabs/teamWritten.ts, audit H2). Codex has no flag for it: a
// worktree takes its main repository's trust, and `-c projects...` does not turn it off (0.165.0, tried). The start gives
// this mode an engine home of its own, which trusts no project (superTabs/start.ts).
diff --git a/cli/src/engines/facets/launch.ts b/cli/src/engines/facets/launch.ts
index ea82d32af..c06e6eb0c 100644
--- a/cli/src/engines/facets/launch.ts
+++ b/cli/src/engines/facets/launch.ts
@@ -143,14 +143,6 @@ export type TrustContract = { home: LaunchHome; file: string } & (
| { format: 'toml'; table: string; key: string; value: string }
)
-/**
- * The engine's one-time warning for the mode that approves everything, which it stops showing once `key` is true in
- * `file` in its home: the setting its own "Yes, I accept" writes. Recorded by core, before a spawn, for a Swarm agent
- * the Swarm starts in that mode (core/agents/create.ts); `false` there is the person's and stays. Applied by
- * kit/folderTrust.ts `recordAcceptanceIn`.
- */
-export interface BypassAcceptanceContract { home: LaunchHome; file: string; key: string }
-
/**
* The engine's question about MCP servers a folder inherits: a project file of servers (`file`, `servers` its map) in a
* folder ABOVE the one it opens, which it asks to use or not as it starts there. Its own "no", the question's default, is
@@ -317,7 +309,6 @@ export interface EngineLaunch {
trust?: TrustContract
/** Recorded with `trust`, for the same folders (kit/inheritedMcp.ts). */
inheritedMcp?: InheritedMcpContract
- bypassAcceptance?: BypassAcceptanceContract
resumeRepair?: ResumeRepairContract
attribution?: AttributionContract
statusLine?: StatusLineContract
diff --git a/cli/src/engines/kit/folderTrust.spec.ts b/cli/src/engines/kit/folderTrust.spec.ts
index 7e631a061..7f9ab5089 100644
--- a/cli/src/engines/kit/folderTrust.spec.ts
+++ b/cli/src/engines/kit/folderTrust.spec.ts
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { launchClaudeConfigDir, launchCodexHome } from '../../lib/engineHomes.js'
import { launch as claude } from '../claude/launch.js'
import { launch as codex } from '../codex/launch.js'
-import { recordAcceptanceIn, recordTrustIn, trustsIn } from './folderTrust.js'
+import { recordTrustIn, trustsIn } from './folderTrust.js'
/** Whether this account may link to a file: Windows lets it only with Developer Mode or as an administrator (Window of Tim,
* #3815), and a person there with neither has no such link to write through. */
@@ -303,31 +303,3 @@ describe('the config each engine actually reads', () => {
})
})
-// Claude Code's "Yes, I accept" for full mode writes this key to its user settings (2.1.310); a Swarm Lead on the Mac
-// Studio waited there before its first turn (2026-10-26).
-describe('full mode\'s warning accepted as the engine records it', () => {
- const key = claude.bypassAcceptance!.key
- it('adds the key to the settings, keeping everything else, once', () => {
- const file = join(mkdtempSync(join(tmpdir(), 'accept-')), 'settings.json')
- writeFileSync(file, JSON.stringify({ theme: 'dark', hooks: { Stop: [] } }))
- expect(recordAcceptanceIn(file, key)).toBe('accepted')
- expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ theme: 'dark', hooks: { Stop: [] }, skipDangerousModePermissionPrompt: true })
- expect(recordAcceptanceIn(file, key)).toBe('already')
- })
-
- it('creates missing settings, its folder too, holding the key alone', () => {
- const file = join(mkdtempSync(join(tmpdir(), 'accept-')), '.claude', 'settings.json')
- expect(recordAcceptanceIn(file, key)).toBe('accepted')
- expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ skipDangerousModePermissionPrompt: true })
- expect(recordAcceptanceIn(file, key)).toBe('already')
- })
-
- it('leaves an unreadable or other-shaped file, and a value the person set, as it was', () => {
- const folder = mkdtempSync(join(tmpdir(), 'accept-')), file = join(folder, 'settings.json')
- for (const text of ['{not json', '[]', JSON.stringify({ [key]: false })]) {
- writeFileSync(file, text)
- expect(recordAcceptanceIn(file, key)).toBe('skipped')
- expect(readFileSync(file, 'utf8')).toBe(text)
- }
- })
-})
diff --git a/cli/src/engines/kit/folderTrust.ts b/cli/src/engines/kit/folderTrust.ts
index ec17633e5..af5982e88 100644
--- a/cli/src/engines/kit/folderTrust.ts
+++ b/cli/src/engines/kit/folderTrust.ts
@@ -108,29 +108,6 @@ function recordJson(trust: JsonTrust, file: string, cwd: string, create = false)
return 'trusted'
}
-/** Record the engine's acceptance of its warning for full mode (facets/launch.ts `BypassAcceptanceContract`) as `key` in
- * the JSON settings `file`. Like trust, only ever adds: a file that is not an object, or a `key` the person set to anything
- * else, stays as it is. A missing file is created holding the key alone: unlike `.claude.json`, which the engine writes on
- * its first run, these settings may not exist yet on a fresh machine, whose first Lead would then stop at the warning. It is
- * created before the engine's hooks are merged into it (core/agents/create.ts), and never over a file made meanwhile. */
-export function recordAcceptanceIn(file: string, key: string): 'accepted' | 'already' | 'skipped' {
- if (!existsSync(file)) {
- mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
- try {
- writeFileSync(file, JSON.stringify({ [key]: true }, null, 2), { mode: 0o600, flag: 'wx' })
- return 'accepted'
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
- }
- }
- let settings: unknown
- try { settings = JSON.parse(readFileSync(file, 'utf8')) } catch { return 'skipped' }
- if (!isPlainObject(settings)) return 'skipped'
- if (settings[key] !== undefined) return settings[key] === true ? 'already' : 'skipped'
- replaceConfigFile(file, JSON.stringify({ ...settings, [key]: true }, null, 2))
- return 'accepted'
-}
-
/** Its own entry, or a folder above it in the same Git repository, says yes: the inheritance Claude Code applies. Unreadable or absent
* settings read as no. */
function jsonTrusts(trust: JsonTrust, file: string, path: string): boolean {
diff --git a/cli/src/engines/launchPrep.spec.ts b/cli/src/engines/launchPrep.spec.ts
index b975b8c3a..965c3a83c 100644
--- a/cli/src/engines/launchPrep.spec.ts
+++ b/cli/src/engines/launchPrep.spec.ts
@@ -1,10 +1,9 @@
-import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
-import { recordAcceptanceIn, recordTrustIn, trustsIn } from './kit/folderTrust.js'
-import { acceptFullMode, folderTrust } from './launchPrep.js'
+import { recordTrustIn, trustsIn } from './kit/folderTrust.js'
+import { folderTrust } from './launchPrep.js'
vi.mock('./kit/homeAdoption.js', async original => ({ ...await original<typeof import('./kit/homeAdoption.js')>(), homeIsNetworkOrDevice: (path: string) => path.startsWith('/net/') }))
-vi.mock('./kit/folderTrust.js', () => ({ trustsIn: vi.fn(() => true), recordTrustIn: vi.fn(() => 'trusted'), recordAcceptanceIn: vi.fn(() => 'accepted') }))
+vi.mock('./kit/folderTrust.js', () => ({ trustsIn: vi.fn(() => true), recordTrustIn: vi.fn(() => 'trusted') }))
describe('folder trust in a network home on Windows', () => {
it.each([['claude', { HOME: '/home/u', CLAUDE_CONFIG_DIR: '/net/x' }], ['codex', { HOME: '/home/u', CODEX_HOME: '/net/x' }]] as const)(
@@ -22,15 +21,3 @@ describe('folder trust in a network home on Windows', () => {
expect(trust.record('/work')).toBe('trusted')
})
})
-
-describe('full mode\'s warning accepted', () => {
- it('in the settings.json of the CLAUDE_CONFIG_DIR the launch reads, never in a network home, and not for an engine without one', () => {
- expect(acceptFullMode('claude', { HOME: '/home/u' })).toBe('accepted')
- expect(recordAcceptanceIn).toHaveBeenLastCalledWith(join('/home/u', '.claude', 'settings.json'), 'skipDangerousModePermissionPrompt')
- expect(acceptFullMode('claude', { HOME: '/home/u', CLAUDE_CONFIG_DIR: '/home/u/moved' })).toBe('accepted')
- expect(recordAcceptanceIn).toHaveBeenLastCalledWith(join('/home/u/moved', 'settings.json'), 'skipDangerousModePermissionPrompt')
- expect(acceptFullMode('claude', { HOME: '/home/u', CLAUDE_CONFIG_DIR: '/net/x' })).toBe('skipped')
- expect(acceptFullMode('codex', { HOME: '/home/u' })).toBeNull()
- expect(recordAcceptanceIn).toHaveBeenCalledTimes(2)
- })
-})
diff --git a/cli/src/engines/launchPrep.ts b/cli/src/engines/launchPrep.ts
index e2ff6e307..a53830c6a 100644
--- a/cli/src/engines/launchPrep.ts
+++ b/cli/src/engines/launchPrep.ts
@@ -8,7 +8,7 @@
import { join } from 'node:path'
import { homeRoots, launchHomeOf } from '../lib/engineHomes.js'
import { homeIsNetworkOrDevice } from './kit/homeAdoption.js'
-import { recordAcceptanceIn, recordTrustIn, trustsIn } from './kit/folderTrust.js'
+import { recordTrustIn, trustsIn } from './kit/folderTrust.js'
import { recordInheritedMcp } from './kit/inheritedMcp.js'
import { repairHistory } from './kit/resumeRepair.js'
import { launchContract } from './launches.js'
@@ -55,15 +55,6 @@ export function folderTrust(engine: AgentEngine, profile?: string | null, enviro
}
}
-/** Record that full mode's one-time warning is accepted in `engine`'s settings, as its "Yes" would (`bypassAcceptance`); null
- * for an engine with no such warning. A network or device home is never opened, as for trust. */
-export function acceptFullMode(engine: AgentEngine, environment?: NodeJS.ProcessEnv): 'accepted' | 'already' | 'skipped' | null {
- const contract = launchContract(engine)?.bypassAcceptance
- if (!contract) return null
- const home = launchHomeOf(contract.home, null, environment)
- return homeIsNetworkOrDevice(home) ? 'skipped' : recordAcceptanceIn(join(home, contract.file), contract.key)
-}
-
/** The session a resume relaunches. `codexHome` is the agent's own engine home, the row's profile. */
export interface ResumeSource {
engine: string
diff --git a/cli/src/lib/engineAccount.ts b/cli/src/lib/engineAccount.ts
index a2e00735a..3e4cb9fa8 100644
--- a/cli/src/lib/engineAccount.ts
+++ b/cli/src/lib/engineAccount.ts
@@ -118,7 +118,7 @@ export async function engineAccount(engine: AgentEngine, deps: EngineAccountDeps
// folder exported in ~/.zshrc is seen through the login shell's environment, captured once per
// process (loginShellEnv.ts), with the daemon's own on top.
const env = deps.env ?? { ...await warmLoginShellEnvironment(), ...process.env }
- // A model API saved on this computer (Models ▸ APIs, or `harness team model set`) serves Claude Code without a
+ // A model API saved on this computer (Models ▸ APIs) serves Claude Code without a
// subscription, so the machine can take Swarm work on it (headless run, 2026-11-03: a working OpenRouter key saved,
// and the account read "not signed in").
const savedApi = (() => {
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index fe4df9cc6..d6eb264d7 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -824,15 +824,12 @@ printf '%s %s' "$harness_status" "$resumed"`], { encoding: 'utf8', stdio: ['igno
.toEqual([engineBin('claude'), '--dangerously-skip-permissions'])
expect(buildEngineCommandArgv('codex', { permissionMode: 'readOnly' }))
.toEqual([engineBin('codex'), '--sandbox', 'read-only', ...CODEX_SCREEN])
- // An older Claude Buddy's saved mode: relaunched like its owner's own session, in full mode (Ken, 11-04, task #2832).
- expect(buildEngineCommandArgv('claude', { permissionMode: 'buddy', bypassPermission: true }))
- .toEqual([engineBin('claude'), '--dangerously-skip-permissions'])
// Team-written work reads none of the branch's own settings, `settings.local.json` included (audit H2).
expect(buildEngineCommandArgv('claude', { permissionMode: 'teamWritten', bypassPermission: true }))
.toEqual([engineBin('claude'), '--dangerously-skip-permissions', '--setting-sources', 'user', '--strict-mcp-config'])
- // An older Codex Buddy's saved mode: full access, as its owner's own session (task #2832).
- expect(buildEngineCommandArgv('codex', { permissionMode: 'readOnlyAsk', bypassPermission: true }))
- .toEqual([engineBin('codex'), '--dangerously-bypass-approvals-and-sandbox', ...CODEX_SCREEN])
+ // An older Buddy's saved mode is no mode: the registry clears it on load (task #4215).
+ expect(permissionModeFlags('claude', 'buddy')).toBeNull()
+ expect(permissionModeFlags('codex', 'readOnlyAsk')).toBeNull()
expect(buildEngineCommandArgv('codex', { permissionMode: 'full' }))
.toEqual([engineBin('codex'), '--dangerously-bypass-approvals-and-sandbox', ...CODEX_SCREEN])
// A mode the engine lacks falls back to the yes/no.
@@ -1286,18 +1283,6 @@ describe('the permission gates', () => {
expect(refusal?.detail).not.toContain('choose Ask')
})
- it('relaunches an older Buddy\'s saved mode as full, never holding it for a flag (task #2832)', async () => {
- const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-gate-'))
- dirs.push(binDir)
- process.env.HARNESS_ENGINE_TEST_PATH = binDir
- fakeEngine(binDir, 'codex', '--dangerously-bypass-approvals-and-sandbox')
- const codex = await dropPermissionFlagIfUnsupported('codex', { permissionMode: 'readOnlyAsk', bypassPermission: false }, bashProbeShell())
- expect([codex.choice.permissionMode, codex.droppedFlag, codex.nativeHold]).toEqual(['readOnlyAsk', null, undefined])
- fakeEngine(binDir, 'claude', '--dangerously-skip-permissions')
- const claude = await dropPermissionFlagIfUnsupported('claude', { permissionMode: 'buddy', bypassPermission: false }, bashProbeShell())
- expect([claude.choice.permissionMode, claude.droppedFlag, claude.nativeHold]).toEqual(['buddy', null, undefined])
- })
-
it('leaves a relaunch alone when the flag is supported', async () => {
const shell = withFakeOpencode('--auto')
const kept = await dropPermissionFlagIfUnsupported('opencode', { permissionMode: 'auto', bypassPermission: true }, shell)
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index 9eb98ea84..5a1bbeab4 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -13,7 +13,7 @@ const env = { cwd: '/work/repo', home: '/home/me', platform: 'linux' as const }
describe('harness new: the words', () => {
it('asks nothing: claude, here, on this machine', () => {
expect(parseNewArgs([], env)).toEqual({
- agent: 'claude', machine: null, cwd: '/work/repo', projectName: null, mode: 'auto', modeGiven: false, prompt: null, name: null, repo: null, acuLimit: null, model: null, json: false,
+ agent: 'claude', machine: null, cwd: '/work/repo', projectName: null, mode: null, prompt: null, name: null, repo: null, acuLimit: null, model: null, json: false,
})
})
@@ -116,7 +116,8 @@ describe('harness new: the words', () => {
expect(here).not.toHaveProperty('projectSource')
expect(typeof here.creationId).toBe('string')
const fresh = newAgentPayload(parseNewArgs(['claude', 'My Game'], env), null)
- expect(fresh).toMatchObject({ engine: 'claude', projectSource: 'new', projectName: 'My-Game', permissionMode: 'auto', bypassPermission: true })
+ expect(fresh).toMatchObject({ engine: 'claude', projectSource: 'new', projectName: 'My-Game', bypassPermission: false })
+ expect(fresh).not.toHaveProperty('permissionMode')
expect(fresh).not.toHaveProperty('cwd')
expect(newAgentPayload(parseNewArgs(['acme/blender', '.'], env), '/work/repo', 'codex')).toMatchObject({ engine: 'codex', dsh: 'acme/blender' })
})
@@ -132,21 +133,24 @@ describe('harness new: the words', () => {
expect(() => parseNewArgs(['devin-cloud', '--acu-limit', '2.5'], env)).toThrow(/1 to 1000/)
})
- it('only sends a permission mode to the engines that take one', () => {
- // The engines with no PERMISSION_MODES row cannot be handed the default `auto`: the daemon refuses
- // a mode the engine has no contract for (INVALID_PERMISSION_MODE), which made `harness new hermes`
- // — and pi, amp, muse, kilo, grok, devin, commandcode, agy, copilot — impossible to run at all.
- for (const agent of ['hermes', 'pi', 'amp', 'muse', 'kilo', 'grok', 'devin', 'commandcode', 'agy', 'copilot']) {
+ // Swarm v3 (task #4215): an agent starts with its owner's own settings. A mode is sent only when the person typed one;
+ // the default `auto` went to every engine that has it, and before that to every engine, which the daemon refused
+ // (INVALID_PERMISSION_MODE) for the ten without a PERMISSION_MODES row.
+ it('sends a permission mode only when the person typed one', () => {
+ for (const agent of ['claude', 'codex', 'opencode', 'hermes', 'pi', 'amp', 'muse', 'kilo', 'grok', 'devin', 'commandcode', 'agy', 'copilot']) {
const payload = newAgentPayload(parseNewArgs([agent], env), '/work/repo')
expect(payload, agent).toMatchObject({ engine: agent, bypassPermission: false })
expect(payload, agent).not.toHaveProperty('permissionMode')
}
- // An engine that has the mode still gets it, and the store harness is judged on the engine it runs on.
- expect(newAgentPayload(parseNewArgs(['opencode'], env), '/work/repo')).toMatchObject({ permissionMode: 'auto', bypassPermission: true })
- expect(newAgentPayload(parseNewArgs(['acme/blender'], env), '/work/repo', 'hermes')).not.toHaveProperty('permissionMode')
+ expect(newAgentPayload(parseNewArgs(['acme/blender'], env), '/work/repo', 'claude')).not.toHaveProperty('permissionMode')
+ expect(newAgentPayload(parseNewArgs(['claude', '--mode', 'auto'], env), '/work/repo')).toMatchObject({ permissionMode: 'auto', bypassPermission: true })
+ expect(newAgentPayload(parseNewArgs(['codex', '--mode', 'full'], env), '/work/repo')).toMatchObject({ permissionMode: 'full', bypassPermission: true })
+ expect(newAgentPayload(parseNewArgs(['claude', '--plan'], env), '/work/repo')).toMatchObject({ permissionMode: 'plan', bypassPermission: false })
+ expect(newAgentPayload(parseNewArgs(['terminal', '--mode', 'auto'], env), '/work/repo')).not.toHaveProperty('permissionMode')
// A mode the person typed stays theirs to get wrong: the daemon refuses it, it is not silently swapped.
expect(newAgentPayload(parseNewArgs(['hermes', '--mode', 'ask'], env), '/work/repo')).toMatchObject({ engine: 'hermes', permissionMode: 'ask', bypassPermission: false })
expect(newAgentPayload(parseNewArgs(['hermes', '--plan'], env), '/work/repo')).toMatchObject({ engine: 'hermes', permissionMode: 'plan', bypassPermission: false })
+ expect(newAgentPayload(parseNewArgs(['hermes', '--mode', 'auto'], env), '/work/repo')).toMatchObject({ engine: 'hermes', permissionMode: 'auto', bypassPermission: false })
})
it('finds the machine by id, name or an unambiguous start of one', () => {
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 5ac6ae36e..8421bc09f 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -41,10 +41,8 @@ export interface NewArgs {
cwd: string | null
/** A new project: its name, or '' to let the clock name it; null when `cwd` is given. */
projectName: string | null
- mode: string
- /** True when `--mode`/`--plan` was typed by the person. The default `auto` is not a request: see
- * [newAgentPayload]. */
- modeGiven: boolean
+ /** The mode the person typed (`--mode`, `--plan`); null when none was: the agent starts in its own default. */
+ mode: string | null
prompt: string | null
name: string | null
/** A cloud coding agent's GitHub repository, `owner/name` or its address, as typed: the machine reads it. */
@@ -73,7 +71,7 @@ export const NEW_USAGE = [
' of your own: Claude Code and Codex ask the person to trust a folder Harness did not make',
'',
' --new [name] a new project, named <name> or after the agent and the time',
- ' --mode <mode> auto (default), ask, plan or full, where the agent has it',
+ ' --mode <mode> auto, ask, plan or full, where the agent has it (default: its own settings)',
' --plan the same as --mode plan',
' --task <t> the first message, sent as the harness starts (--prompt is the same)',
' -- <words…> everything after -- is the first message, unquoted:',
@@ -103,8 +101,7 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string; p
let machine: string | null = null
let folder: string | null = null
let projectName: string | null = null
- let mode = 'auto'
- let modeGiven = false
+ let mode: string | null = null
let prompt: string | null = null
let name: string | null = null
let repo: string | null = null
@@ -126,8 +123,8 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string; p
break
}
if (word === '--json') json = true
- else if (word === '--plan') { mode = 'plan'; modeGiven = true }
- else if (word === '--mode') { mode = value(word, i); modeGiven = true; i++ }
+ else if (word === '--plan') mode = 'plan'
+ else if (word === '--mode') { mode = value(word, i); i++ }
else if (word === '--prompt' || word === '--task') { prompt = value(word, i); i++ }
else if (word === '--name') { name = value(word, i); i++ }
// The app's New Harness box sends a model the same way; `harness new` had no word for it, so an agent asked to
@@ -176,7 +173,7 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string; p
// What the cloud service would refuse, refused before anything is sent, in its words.
const cloudRefusal = isCloudAgent(words[0]) ? cloudRequestRefusal(words[0], prompt ?? '', [repo]) : null
if (cloudRefusal) throw new NewUsageError(cloudRefusal)
- if (!MODES.has(mode)) throw new NewUsageError(`--mode is one of ${[...MODES].join(', ')}.`)
+ if (mode !== null && !MODES.has(mode)) throw new NewUsageError(`--mode is one of ${[...MODES].join(', ')}.`)
if (words.length > 2) throw new NewUsageError(`Too many words: ${words.slice(2).join(' ')}.`)
if (words[1] !== undefined) {
if (projectName !== null && projectName !== '') throw new NewUsageError('Name the new project once.')
@@ -212,7 +209,7 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string; p
if (machine === null) cwd = env.cwd
else projectName = ''
}
- return { agent: words[0] ?? 'claude', machine, cwd, projectName, mode, modeGiven, prompt, name, repo, acuLimit, model, json }
+ return { agent: words[0] ?? 'claude', machine, cwd, projectName, mode, prompt, name, repo, acuLimit, model, json }
}
/** The `agent_create` payload for [args]: the same fields the app's box sends. [baseEngine] is the
@@ -222,19 +219,13 @@ export function newAgentPayload(args: NewArgs, cwd: string | null, baseEngine =
const harness = args.agent.includes('/') ? args.agent : null
const terminal = args.agent === 'terminal'
const engine = harness ? baseEngine : args.agent
- // A mode is only an engine's to take. The usage says `--mode` applies "where the agent has it", but
- // the default `auto` went to every engine, and the daemon refuses a mode an engine has no
- // `PERMISSION_MODES` row for (`INVALID_PERMISSION_MODE` in backendSocket.ts) — so the ten engines
- // without a row (hermes, pi, amp, muse, kilo, grok, devin, commandcode, agy, copilot) could not be
- // created from the CLI at all, and neither could a store harness running on one of them.
- // An unasked-for default is therefore left out: the engine opens in its own default mode. A mode the
- // person typed is still sent, so the daemon's refusal — "refused rather than quietly launched in
- // some other mode" — stays the answer where a choice was actually made.
- const hasMode = ENGINE_NAMES.has(engine) && permissionModeFlags(engine as AgentEngine, args.mode) !== null
- const mode = args.modeGiven || hasMode ? args.mode : null
- // A row that keeps claiming Auto while running without the flag is the more expensive lie, so the
- // bypass is only claimed where the engine really has the mode it was asked for.
- const approves = mode !== null && (mode === 'auto' || mode === 'full') && hasMode
+ // A mode is sent only when the person typed one (Swarm v3, task #4215): the agent starts with its owner's own settings.
+ // The default `auto` once went to every engine, which the daemon refused for the ten with no PERMISSION_MODES row
+ // (`INVALID_PERMISSION_MODE`), and then to every engine that had it. A typed mode is sent as typed, so the daemon's
+ // refusal stays the answer where a choice was made. A row that claims Auto while running without the flag is the more
+ // expensive lie, so the bypass is only claimed where the engine has the mode.
+ const mode = terminal ? null : args.mode
+ const approves = (mode === 'auto' || mode === 'full') && ENGINE_NAMES.has(engine) && permissionModeFlags(engine as AgentEngine, mode) !== null
return {
engine,
...(harness ? { dsh: harness } : {}),
@@ -242,8 +233,8 @@ export function newAgentPayload(args: NewArgs, cwd: string | null, baseEngine =
projectSource: 'new',
...(args.projectName ? { projectName: projectFolderSlug(args.projectName) } : {}),
}),
- bypassPermission: !terminal && approves,
- ...(terminal || mode === null ? {} : { permissionMode: mode }),
+ bypassPermission: approves,
+ ...(mode === null ? {} : { permissionMode: mode }),
...(args.prompt ? { prompt: args.prompt } : {}),
...(args.name ? { name: args.name } : {}),
...(args.repo ? { repositoryUrl: args.repo } : {}),
@@ -563,10 +554,10 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
// Full mode turns off the new agent's own permission checks and sandbox (`--dangerously-skip-permissions`,
// `--dangerously-bypass-approvals-and-sandbox`). Harness's agent commands run without the person being asked
// (engines/facets/hooks.ts HarnessAllowance), so a sandboxed agent could have started one with any task and no one
- // asked: the review of #1232. Auto, the default, keeps each engine's own checks. The person still chooses full.
+ // asked: the review of #1232. With no mode it starts in its owner's own default. The person still chooses full.
if (origin && args.mode === 'full') {
throw new Error('An agent cannot start a harness in full mode: it would run with its permission checks and sandbox off, '
- + 'and no one was asked. Start it without --mode (auto, where its own checks run), or ask the person to start it in full mode. '
+ + 'and no one was asked. Start it without --mode (its owner\'s own default mode), or ask the person to start it in full mode. '
+ 'Nothing was started.')
}
let machineId = deps.localMachineId
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index e30c36776..3383c69c8 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -620,6 +620,50 @@ describe('registry remote display names', () => {
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toHaveLength(2)
})
+ // Swarm v3 (task #4215): until then Harness itself started every Swarm agent in full mode, and an older Buddy in `buddy` or
+ // `readOnlyAsk`; a relaunch reapplies a saved mode, so those agents kept skipping permissions after the fix.
+ it('clears, once, the permission modes Harness forced on saved agents, and keeps the person\'s own', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({ agentId: 'template', engine: 'claude', tmuxPane: '%50', processIdentity: processIdentity(950) })
+ const [row] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
+ const at = (agentId: string, pane: string, fields: Record<string, unknown>) => ({ ...row, agentId, sessionId: '', processIdentity: null,
+ tmuxPane: pane, runtimes: [{ backend: 'tmux', paneId: pane }], primaryRuntimeKey: `tmux\u0000${pane}`, ...fields })
+ const swarmSkill = { role: 'lead', key: 'swarm-lead' }
+ const saved = [
+ at('swarm-full', '%51', { swarmSkill, permissionMode: 'full', bypassPermission: true }),
+ at('old-buddy', '%52', { swarmSkill: { role: 'buddy', key: 'swarm-buddy' }, permissionMode: 'buddy', bypassPermission: true }),
+ at('old-codex-buddy', '%53', { permissionMode: 'readOnlyAsk', bypassPermission: true }),
+ at('own-full', '%54', { permissionMode: 'full', bypassPermission: true }),
+ at('swarm-ask', '%55', { swarmSkill, permissionMode: 'ask' }),
+ at('team-written', '%56', { swarmSkill, permissionMode: 'teamWritten', bypassPermission: true }),
+ ]
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(saved), { mode: 0o600 })
+ // As a machine upgrading from a build before the sweep: no marker yet.
+ rmSync(join(dataDir, 'registry-own-modes'), { force: true })
+
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+
+ for (const id of ['swarm-full', 'old-buddy', 'old-codex-buddy']) {
+ expect(reloaded.byAgent(id)?.permissionMode, id).toBeUndefined()
+ expect(reloaded.byAgent(id)?.bypassPermission, id).toBeUndefined()
+ }
+ expect([reloaded.byAgent('own-full')?.permissionMode, reloaded.byAgent('own-full')?.bypassPermission]).toEqual(['full', true])
+ expect(reloaded.byAgent('swarm-ask')?.permissionMode).toBe('ask')
+ expect(reloaded.byAgent('team-written')?.permissionMode).toBe('teamWritten')
+ const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8')) as Array<Record<string, unknown>>
+ expect(persisted.find(entry => entry.agentId === 'swarm-full')).not.toHaveProperty('permissionMode')
+ expect(persisted.find(entry => entry.agentId === 'swarm-full')).not.toHaveProperty('bypassPermission')
+
+ // Once: full mode a person chooses for a Swarm agent afterwards is theirs, and a later load keeps it.
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(persisted.map(entry => entry.agentId === 'swarm-full'
+ ? { ...entry, permissionMode: 'full', bypassPermission: true } : entry)), { mode: 0o600 })
+ const { registry: later } = await loadRegistryModule()
+ later.load()
+ expect([later.byAgent('swarm-full')?.permissionMode, later.byAgent('swarm-full')?.bypassPermission]).toEqual(['full', true])
+ })
+
it('repairs a Codex parent registry entry overwritten with a child rollout', async () => {
const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index b759d4c0d..dd3728f19 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -392,6 +392,8 @@ const NAMES_FILE = join(env.ADAPTER_DATA_DIR, 'agent-names.json')
const BOOT_FILE = join(env.ADAPTER_DATA_DIR, 'registry-boot')
const LOCK_DIR = join(env.ADAPTER_DATA_DIR, 'registry.json.lock')
const PRE_V2_BACKUP_FILE = join(env.ADAPTER_DATA_DIR, 'registry.pre-v2.json')
+/** Written once this machine's saved agents are cleared of the permission modes Harness forced (`withoutForcedModes`). */
+const OWN_MODES_FILE = join(env.ADAPTER_DATA_DIR, 'registry-own-modes')
const NAME_OVERRIDES = new Map<string, string>()
const PANE_RE = /^%\d+$/
@@ -638,6 +640,23 @@ function withoutRetiredRows(stored: readonly unknown[]): { rows: unknown[]; drop
return { rows, dropped: stored.length - rows.length, changed: cleaned.some((row, i) => row !== stored[i]) }
}
+/**
+ * Swarm v3 (task #4215): until then Harness itself started every Swarm agent in full mode, and an older Buddy in `buddy` or
+ * `readOnlyAsk`; nobody chose those, and a relaunch reapplies a saved mode. So the first load of a build with this clears them,
+ * once (`OWN_MODES_FILE`): full mode a person chooses for a Swarm agent afterwards is theirs and kept. Review after 2027-01-07.
+ */
+function withoutForcedModes(rows: Array<Partial<RegisteredSession>>): { rows: Array<Partial<RegisteredSession>>; cleared: number } {
+ let cleared = 0
+ const kept = rows.map((row) => {
+ const mode: unknown = row?.permissionMode
+ if (!(mode === 'buddy' || mode === 'readOnlyAsk' || (mode === 'full' && parseSwarmSkill(row.swarmSkill)))) return row
+ cleared++
+ const { permissionMode: _mode, bypassPermission: _bypass, ...own } = row
+ return own
+ })
+ return { rows: kept, cleared }
+}
+
/** A legacy `tmuxPane` adds a tmux runtime unless it is a listed runtime's own projection (`paneProjection`). */
function normalizedRuntimes(raw: unknown, legacyTmuxPane?: unknown): TerminalRuntimeRef[] {
const fromArray = Array.isArray(raw) ? raw.filter(validTerminalRuntime) : []
@@ -1266,16 +1285,23 @@ class Registry {
this.quarantine('contains a malformed v2 row')
return
}
- const arr = parsed as Array<Partial<RegisteredSession>>
+ let arr = parsed as Array<Partial<RegisteredSession>>
for (const row of arr) {
const id = rowId(row)
if (id) this.persistedBaseline.set(id, rowFingerprint(row))
}
+ // After the baseline, so the save below writes the cleared rows rather than merging the disk's back in.
+ const ownModes = !existsSync(OWN_MODES_FILE)
+ if (ownModes) {
+ const swept = withoutForcedModes(arr)
+ if (swept.cleared) console.log(`[registry] ${swept.cleared} agent(s) start with their owner's own permission settings again`)
+ arr = swept.rows
+ }
// The rollback copy is the file as found, retired runtimes and all — not the cleaned rows.
if (arr.some((row) => row.schemaVersion !== 2)) {
atomicWriteJson(PRE_V2_BACKUP_FILE, stored, true)
}
- let changed = strippedRetired
+ let changed = strippedRetired || (ownModes && arr.some((row, i) => row !== parsed[i]))
if (rebooted) {
this.rebooted = true
console.log(`[registry] machine rebooted since last run — ${arr.length} agent(s) kept with their process identity cleared (stale panes, restored on start)`)
@@ -1493,12 +1519,13 @@ class Registry {
return
}
if (changed) this.save()
+ if (ownModes) atomicWriteJson(OWN_MODES_FILE, Date.now())
} catch (error) {
if (error instanceof SyntaxError) this.quarantine(`is not JSON (${error.message})`)
else if (existsSync(FILE)) {
this.writeBlocked = true
console.error('[registry] registry is unreadable; refusing to overwrite it:', error instanceof Error ? error.message : error)
- }
+ } else atomicWriteJson(OWN_MODES_FILE, Date.now())
// A genuinely absent file starts empty. A file that cannot be opened safely (a symlink, another
// owner, open permissions) is left exactly as it is, and nothing is written over it.
}
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index bc674f962..aa2c4cc57 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -404,4 +404,15 @@ describe('bypassPermissionFor', () => {
await expect(bypassPermissionFor({}, live)).resolves.toBe(true)
expect(live).toHaveBeenCalledTimes(1)
})
+
+ // Swarm v3 (task #4215): a Swarm agent's mode is its person's choice, or none. One Harness started in full mode, cleared
+ // since, still runs with that flag: read back, its restart or retarget came back in Auto, which nobody chose.
+ it('never asks a Swarm agent\'s live process: with no mode it relaunches approving nothing', async () => {
+ const live = probe()
+ const swarmSkill = { role: 'coordinator' as const, key: 'swarm-lead' }
+ await expect(bypassPermissionFor({ swarmSkill }, live)).resolves.toBe(false)
+ expect(live).not.toHaveBeenCalled()
+ // The mode its person chose still counts.
+ await expect(bypassPermissionFor({ swarmSkill, permissionMode: 'full' }, live)).resolves.toBe(true)
+ })
})
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index 72b5186ef..2a6c6d7fa 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -26,11 +26,14 @@ import { permissionModeApproves } from './engineLaunch.js'
* mode itself; this only settles the yes/no the engines without a mode table launch with.
*/
export async function bypassPermissionFor(
- session: Pick<RegisteredSession, 'permissionMode' | 'bypassPermission'>,
+ session: Pick<RegisteredSession, 'permissionMode' | 'bypassPermission' | 'swarmSkill'>,
probeLive: () => Promise<boolean>,
): Promise<boolean> {
if (session.permissionMode) return permissionModeApproves(session.permissionMode)
if (session.bypassPermission !== undefined) return session.bypassPermission
+ // A Swarm agent's mode is its person's choice, or none (task #4215). One Harness started in full mode, cleared since,
+ // still runs with that flag until it relaunches: read back, it would come back in Auto, which nobody chose.
+ if (session.swarmSkill) return false
return probeLive()
}
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index aa8545fac..7e31a910e 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -10,7 +10,7 @@ vi.mock('../team/config.js', async (original) => ({ ...await original<object>(),
const started = vi.hoisted(() => ({ owner: 'peer' as string | null }))
vi.mock('./buddyGuard.js', async (original) => ({ ...await original<object>(), buddyOwnerOf: () => started.owner }))
import { SWARM_TOOLS_SKILL } from './swarmTools.js'
-import { swarmToolsSheet, type ToolsRole } from './swarmToolSheets.js'
+import { TOOLS_ROLES, swarmToolsSheet, type ToolsRole } from './swarmToolSheets.js'
import { prepareSwarmSkill, parseSwarmSkill, recordSwarmSkillNotice, refreshSwarmSkill, roleFromWire, skillFile } from './swarmSkills.js'
import { agentLaunchArgs } from './agentAttribution.js'
import { buildLaunchOverrides } from './launchOverrides.js'
@@ -27,6 +27,16 @@ const fixture = () => { const root = mkdtempSync(join(tmpdir(), 'swarm-skills-')
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
describe('built-in Swarm skills', () => {
+ it('say nothing of Team accounts, which Swarm v3 has none of (#4221): the role skills, the tools manual and every sheet', () => {
+ const team = /Team account|Team agent/i
+ for (const role of ['lead', 'dev', 'review', 'buddy'] as const) for (const mode of ['default', 'orchestration'] as const) {
+ const prepared = prepareSwarmSkill(fixture(), { role, key: `${role}-${mode}`, mode })
+ expect(readFileSync(prepared.file, 'utf8'), `${role} ${mode}`).not.toMatch(team)
+ }
+ expect(SWARM_TOOLS_SKILL).not.toMatch(team)
+ for (const role of TOOLS_ROLES) expect(swarmToolsSheet(role), role).not.toMatch(team)
+ })
+
it('writes the tools skill beside the role\'s and sends the agent to its instructions', () => {
for (const role of ['lead', 'dev', 'review'] as const) for (const mode of ['default', 'orchestration'] as const) {
const workspace = fixture(), saved = { role, key: `${role}-${mode}`, mode }
@@ -213,10 +223,10 @@ describe('built-in Swarm skills', () => {
// iPhone): the Builder's and the Reviewer's check, in both modes, and the Lead's move, in both modes.
const toolCheck = '- In your first minutes, check that this machine and account have every tool, device and sign-in you need to do the work yourself (for example flutter, xcodebuild, a connected iPhone, a signed-in gh or App Store account, docker); a device step the brief leaves to a person stays a "Needs:" line. If one is missing, mark blocked at once and stop (see Blocked).\n'
// The stop lives in the Builder's Blocked section, the only place its skill lets it stop (review of #2096).
- const missingStop = '- A missing tool, device or sign-in on this machine and account: mark blocked at once, naming what is missing, the machine, and whether it is the owner\'s or the Team account (no emails or tokens), and stop: the Lead moves the task. Never wait silently.\n'
+ const missingStop = '- A missing tool, device or sign-in on this machine and account: mark blocked at once, naming what is missing, the machine (no emails or tokens), and stop: the Lead moves the task. Never wait silently.\n'
// The Reviewer's, at the end of its first paragraph.
- const reviewCheck = ' In your first minutes, check that this machine and account have every tool, device and sign-in the review needs; if one is missing, mark blocked at once, naming what is missing, the machine, and whether it is the owner\'s or the Team account (no emails or tokens), and stop: the Lead moves the task.'
- const moveMissing = '- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. A Mac\'s own account and its Team account are different: the Team account has none of the owner\'s tools, devices or sign-ins. If none has it, tag the requester with the choice.\n'
+ const reviewCheck = ' In your first minutes, check that this machine and account have every tool, device and sign-in the review needs; if one is missing, mark blocked at once, naming what is missing, the machine (no emails or tokens), and stop: the Lead moves the task.'
+ const moveMissing = '- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. If none has it, tag the requester with the choice.\n'
// The Builder's check replaces its machine-or-device line; the Default Builder keeps the person part of it. The orchestration
// Builder's "missing machine" now means another machine, since its own is the stop above.
const failFast: Array<['orchestration' | 'default', 'lead' | 'dev', string, string]> = [
@@ -1088,8 +1098,9 @@ describe('a Buddy\'s folder', () => {
// built-in text it launched with, for a Swarm with no instructions, and a row an older CLI saved relaunches onto its own.
describe('role kinds keep their role files', () => {
/** The whole file a Reviewer's launch writes in each mode, byte for byte, as before role kinds (its post rules as of #3057). */
- // Task #3029's ask-a-person line changed both; the byte-for-byte tests above show it is the only change.
- const REVIEW = { orchestration: 'a308926d41b60cdbe3405d25b9c89a2c8924cfe3b65a1d6a0ab3106165279316', default: '9a010ed13a8b1c1019a8aee156baa94c0cfe9c657d2a614ff24fc746a454663e' }
+ // Task #3029's ask-a-person line changed both, and #4221 took the Team account out of the missing-tool line; the
+ // byte-for-byte tests above show those are the only changes.
+ const REVIEW = { orchestration: '278287b99bba7edf3cac6194a72c3110d973e2974835ec01afdd6a9953f430ca', default: 'a6215d1202c1a95be0408cc5008247c6626b5716aca140b8382c2195ae16836d' }
const folder = (workspace: string, key: string, name: string) =>
join(realpathSync(workspace), '.harness', 'runtime', sha256(key), 'swarm', 'skills', name)
it('keeps each session\'s role file', () => {
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 9d59e38ab..203598f62 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -113,7 +113,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- When you need a person to act or decide, tag them in the message by @username or id, never by email.
- Ask people for decisions in one place: decision.ask puts up to 10 questions to one person at once, each with 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until they answer: a notice in that conversation tells you, and harness super-tab decisions --answered shows the answer. A decision is not a private channel: to tell one person something directly, send person.tell; it lands in their Buddy chat, which you cannot read. Project members watching your terminal see what you send. Put nothing there you wouldn't say in the project chat.
- Blocked: change something. Give more context, re-route to a stronger model, cut the work smaller, or fix the plan. Never resend the same thing to the same model.
-- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. A Mac's own account and its Team account are different: the Team account has none of the owner's tools, devices or sign-ins. If none has it, tag the requester with the choice.
+- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. If none has it, tag the requester with the choice.
- Rulings, not stalls: when a Builder hits an ambiguity you can settle, settle it and record "Ruling: what — why — cost if wrong". Ask the person only what changes what gets built.
- Each time you are woken, look at active work. Ask a worker with active work that has said nothing for 20 minutes; when the Swarm tells you a task stalled (quiet or orphaned), act on it within minutes: nudge its agent, reassign it, or post in its chat why it waits; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.
- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
@@ -272,7 +272,7 @@ With several clearly separate failures, you may start read-only subagents to inv
- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.
- Can't go on: mark blocked with why, and what would unblock you.
- Post a "Needs:" line, continue the independent parts, and mark working again once it moves.
-- A missing tool, device or sign-in on this machine and account: mark blocked at once, naming what is missing, the machine, and whether it is the owner's or the Team account (no emails or tokens), and stop: the Lead moves the task. Never wait silently.
+- A missing tool, device or sign-in on this machine and account: mark blocked at once, naming what is missing, the machine (no emails or tokens), and stop: the Lead moves the task. Never wait silently.
- Stop for a decision only for an irreversible or destructive step, a security-sensitive action, an effect outside your worktree, or a brief so broken that every path is a guess. Settle other ambiguity with the narrowest safe reading and a Ruling, and keep going. Another machine the work needs, test data, or a person's hands is still a "Needs:" line; continue the independent parts.
- Escalate to the Lead with a "Needs:" line when the work needs an architecture choice between valid options, code you cannot understand, or restructuring the brief did not plan; or when you doubt your approach or keep reading without progress. Keep doing the independent parts; bad work is worse than none.
- Read an ambiguous answer in its narrowest safe sense, and record that reading.
@@ -364,7 +364,7 @@ You give an independent verdict on one revision. You judge the work product, not
4. Project instructions (AGENTS.md, CLAUDE.md, CONTRIBUTING) outrank this skill; judge against them.
## 1. Inputs
-You get the goal, constraints, owned code, acceptance checks, most-likely-wrong list, the Builder's rulings, the revision range and the Builder's handoff. You do not get the chat history. If something essential is missing, ask the Lead once. Start reading within 30 minutes of the request; if you cannot, tell the Lead. In your first minutes, check that this machine and account have every tool, device and sign-in the review needs; if one is missing, mark blocked at once, naming what is missing, the machine, and whether it is the owner's or the Team account (no emails or tokens), and stop: the Lead moves the task.
+You get the goal, constraints, owned code, acceptance checks, most-likely-wrong list, the Builder's rulings, the revision range and the Builder's handoff. You do not get the chat history. If something essential is missing, ask the Lead once. Start reading within 30 minutes of the request; if you cannot, tell the Lead. In your first minutes, check that this machine and account have every tool, device and sign-in the review needs; if one is missing, mark blocked at once, naming what is missing, the machine (no emails or tokens), and stop: the Lead moves the task.
## 2. What to check, in order
1. Brief compliance: everything asked for is present; when the brief lists several files each with its own change, check that each has it. Flag each deviation so the Builder can say if it was intended. If the brief or spec itself is wrong, say so.
@@ -479,7 +479,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.
- When you need a person to act or decide, tag them in the message by @username or id, never by email.
- Ask people for decisions in one place: decision.ask puts up to 10 questions to one person at once, each with 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until they answer: a notice in that conversation tells you, and harness super-tab decisions --answered shows the answer. A decision is not a private channel: to tell one person something directly, send person.tell; it lands in their Buddy chat, which you cannot read. Project members watching your terminal see what you send. Put nothing there you wouldn't say in the project chat.
-- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. A Mac's own account and its Team account are different: the Team account has none of the owner's tools, devices or sign-ins. If none has it, tag the requester with the choice.
+- A Builder or Reviewer blocked on a missing tool, device or sign-in: within minutes, route the task again with what was missing in its needs (fix its required machine if that is the one without it), assign it to a machine and account that has it, then stop the blocked agent unless other work fits its machine. If none has it, tag the requester with the choice.
- Settle ambiguities you can and record "Ruling: what — why — cost if wrong".
- When a worker finishes: reuse, keep or stop. Prefer stop.
- Keep the project's Next up in the order work should start: work.queue with after (null for the top) moves a task, and notBefore (YYYY-MM-DD) marks a promise such as removing a route after a date.
@@ -568,7 +568,7 @@ You finish one group's work completely, inside its brief, as if nobody will come
- A person's decision: mark needs-human with one short question.
- When you know who decides, add ask to that needs-human (the person, 2 to 5 options, the one you recommend, what it unblocks) and keep working on your recommendation, marked provisional, until a notice says it was answered; read the answer with harness super-tab decisions --answered.
- Can't go on: mark blocked with why and what would unblock you, then do the independent parts.
-- A missing tool, device or sign-in on this machine and account: mark blocked at once, naming what is missing, the machine, and whether it is the owner's or the Team account (no emails or tokens), and stop: the Lead moves the task. Never wait silently.
+- A missing tool, device or sign-in on this machine and account: mark blocked at once, naming what is missing, the machine (no emails or tokens), and stop: the Lead moves the task. Never wait silently.
- Stop and ask before anything irreversible, security-sensitive, outside your worktree, visible or audible on a real device, or moving hardware.
## 4. Hand off
@@ -619,7 +619,7 @@ You give an independent verdict on one revision. Work otherwise the way you norm
4. Project instructions (AGENTS.md, CLAUDE.md, CONTRIBUTING) outrank this skill.
## 1. When
-Start within 30 minutes of being asked; oldest ready work first. If you cannot, tell the Lead. In your first minutes, check that this machine and account have every tool, device and sign-in the review needs; if one is missing, mark blocked at once, naming what is missing, the machine, and whether it is the owner's or the Team account (no emails or tokens), and stop: the Lead moves the task.
+Start within 30 minutes of being asked; oldest ready work first. If you cannot, tell the Lead. In your first minutes, check that this machine and account have every tool, device and sign-in the review needs; if one is missing, mark blocked at once, naming what is missing, the machine (no emails or tokens), and stop: the Lead moves the task.
## 2. What to look for
- Wrong behaviour, missed cases, and what the brief asked for but is missing.
diff --git a/cli/src/lib/swarmToolSheets.ts b/cli/src/lib/swarmToolSheets.ts
index 7571c1a21..3f6154242 100644
--- a/cli/src/lib/swarmToolSheets.ts
+++ b/cli/src/lib/swarmToolSheets.ts
@@ -76,7 +76,7 @@ const ENTRIES: readonly SheetEntry[] = [
OFF('- `@Name`'),
OFF('- A reply (`--reply-to`)'),
T('- A post that names no one', 'A post naming no one reaches no agent, except in a task or step: there it reaches the assigned agent.'),
- T('- In a task a Harness Team agent wrote', 'In a task a Team agent wrote, a main-account agent cannot join: the post is delivered and says notReached.', 'engineer', 'ert'),
+ T('- A post naming an agent that may not join', 'A post naming an agent that may not join its task is delivered without it and says notReached.', 'engineer', 'ert'),
T('- The coordinator gets a post only', 'The PM hears your work through work.status: never post it a result, verdict or acknowledgement.'),
T('- In the project chat', 'In the project chat `--to` adds no agent: name only the coordinator.'),
OFF('- A post stays inside your project'),
@@ -128,10 +128,9 @@ const ENTRIES: readonly SheetEntry[] = [
T('- After a restart', 'After a restart read the recovery notice and the last checkpoint; never replay old input.'),
OFF('Many people talk at once.'),
T('- The Swarm\'s people are its members', 'People are the Swarm\'s members (`status`): match a name before asking for an invitation.', 'pm', 'p'),
- OFF('- A Mac in the Swarm runs agents', 'pm'),
OFF('- An agent a person started', 'pm'),
- T('- A tool missing in a Team account', 'A tool missing in a Team account: start an agent there to install it; never ask a person to sudo.', 'pm', 'p'),
- T('- An agent on another person\'s machine', 'In a Team account or on another person\'s machine, git and gh come through the Swarm\'s GitHub App for your task; nobody signs in.', 'engineer', 'ert'),
+ T('- A tool missing on a machine', 'A tool missing on a machine: start an agent there to install it; never ask a person to sudo.', 'pm', 'p'),
+ T('- An agent on another person\'s machine', 'On another person\'s machine, git and gh come through the Swarm\'s GitHub App for your task; nobody signs in.', 'engineer', 'ert'),
OFF('- Issues and changes to .github', 'engineer'),
T('- Never ask for a token', 'Never ask for a token in the chat or a file.', 'core', 'pert'),
T('- Ask a person only', 'Ask a person only for what no agent can do, one step at a time.', 'pm', 'p'),
@@ -207,7 +206,7 @@ const SOURCE: Readonly<Record<string, string>> = {
"- `@Name`": "768716eccb0b",
"- A reply (`--reply-to`)": "55b20de01505",
"- A post that names no one": "d9ebfaef9d01",
- "- In a task a Harness Team agent wrote": "29dcb36a6515",
+ "- A post naming an agent that may not join": "76f81e8e9b0c",
"- The coordinator gets a post only": "e8ee266e21c4",
"- In the project chat": "467f7b44f999",
"- A post stays inside your project": "0e0513801142",
@@ -258,10 +257,9 @@ const SOURCE: Readonly<Record<string, string>> = {
"- After a restart": "dea210ac457d",
"Many people talk at once.": "021d79f77b50",
"- The Swarm's people are its members": "271a685f8a32",
- "- A Mac in the Swarm runs agents": "857b62b02a06",
- "- An agent a person started": "56970a37cfbd",
- "- A tool missing in a Team account": "6c8c8ade8d3c",
- "- An agent on another person's machine": "ef1717f3e636",
+ "- An agent a person started": "cb328a6bd255",
+ "- A tool missing on a machine": "367aec14ceec",
+ "- An agent on another person's machine": "89e8aa0a5815",
"- Issues and changes to .github": "c6d9f3fc034f",
"- Never ask for a token": "4946b26723fd",
"- Ask a person only": "93a3e16507f7",
diff --git a/cli/src/lib/swarmTools.spec.ts b/cli/src/lib/swarmTools.spec.ts
index 11289d266..a7989cc71 100644
--- a/cli/src/lib/swarmTools.spec.ts
+++ b/cli/src/lib/swarmTools.spec.ts
@@ -15,12 +15,12 @@ describe('SWARM_TOOLS_SKILL', () => {
// Project instructions, phase 4: the server refuses only facts and access, routing rules live in the instructions, and
// agents change the instructions instead of rules or skill sets.
// Ken, 2026-11-03: a new project's coordinator sent people to sudo into a Mac's Team account, sign it in to GitHub and save
- // tokens in files, not knowing how the Swarm runs work on another person's Mac.
+ // tokens in files, not knowing how the Swarm runs work on another person's Mac. Swarm v3 has no Team accounts (#4221).
it('says how accounts, machines and the GitHub App work, and what never to ask a person', () => {
const at = SWARM_TOOLS_SKILL.indexOf('## Accounts and machines')
expect(at).toBeGreaterThan(0)
const section = SWARM_TOOLS_SKILL.slice(at, SWARM_TOOLS_SKILL.indexOf('## Shared machines and secrets'))
- for (const part of ['Team account', 'nobody types in it', 'none of the owner\'s tools', 'in their own session', 'handoff',
+ for (const part of ['in their own session', 'handoff',
'## GitHub', 'GitHub App', 'pull requests', 'where the repository\'s installation of the App granted it', 'Never ask a person to sudo', 'Never ask for a token']) expect(section).toContain(part)
})
// Task #2924 (Dee, 2026-11-04): the agent doing the work posts in its project chat itself, joining nobody there (#2207).
diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.ts
index cdf40d324..f8290133b 100644
--- a/cli/src/lib/swarmTools.ts
+++ b/cli/src/lib/swarmTools.ts
@@ -38,7 +38,7 @@ Every command starts \`harness super-tab --tab TAB\` (your tab id is in your lau
- \`@Name\` in TEXT names an agent of this conversation the same way, when only one agent there goes by that name and no person does.
- A reply (\`--reply-to\`) also reaches the agent who wrote the message it answers.
- A post that names no one reaches no agent, except in a task or step, where it reaches the agent assigned there unless that is you. It stays readable in its conversation, and the people it tags are still told; its result says when it reached no agent.
-- In a task a Harness Team agent wrote, an agent of the main account may not join: a post naming it is still delivered, without it, and its result says notReached with that agent named. Nothing is wrong with your post; the PM hands that work on.
+- A post naming an agent that may not join its task is still delivered, without it, and its result says notReached with that agent named. Nothing is wrong with your post; the PM hands that work on.
- The coordinator gets a post only when it is named: your status (done, needs_human, blocked) is how it hears your work, so never post it a result, a verdict, a Ready or an acknowledgement.
- In the project chat, an agent with a task or step in the project posts and reacts without joining it, and a person's answer to its line reaches it; \`--to\` there adds no agent, so name only the coordinator.
- A post stays inside your project. Private chats and Buddy chats keep their own members.
@@ -126,12 +126,11 @@ Many people talk at once. Answer a message in the main chat right below it with
## Accounts and machines
- The Swarm's people are its members (\`status\`); someone may go by another name or email in the chat. Match a name to a member before asking for an invitation.
-- A Mac in the Swarm runs agents in one of two accounts. Its owner's own account runs the owner's projects, with the owner's tools and sign-ins; the owner can watch and type there. Its Harness Team account, a separate macOS user Harness made, runs other people's projects: nobody types in it, its agents run with full permissions, and it has none of the owner's tools, devices or sign-ins.
-- An agent a person started in their own session, outside the Swarm, cannot be assigned or messaged. To bring its work in, start an agent in the Swarm (on that person's Mac, another person's project runs in its Team account) and ask the person to have the old agent write a handoff to attach in the chat.
-- A tool missing in a Team account: start an agent there to install it in its own home; it needs no password. Never ask a person to sudo into the Team account, or to sign it in to GitHub or anything else.
+- An agent a person started in their own session, outside the Swarm, cannot be assigned or messaged. To bring its work in, start an agent in the Swarm (on that person's own computer) and ask the person to have the old agent write a handoff to attach in the chat.
+- A tool missing on a machine: start an agent there to install it in its own home. Never ask a person to sudo, or to sign anything in to GitHub for an agent's work.
## GitHub
-- An agent on another person's machine, and every agent in a Team account, gets git and gh through the Swarm's GitHub App for its task: clone, fetch, push branches, open, update and comment on pull requests, read checks. Nobody signs in for it.
+- An agent on another person's machine gets git and gh through the Swarm's GitHub App for its task: clone, fetch, push branches, open, update and comment on pull requests, read checks. Nobody signs in for it.
- Issues and changes to .github/workflows: the token writes issues (comment, label) and pushes workflow changes only where the repository's installation of the App granted it; elsewhere GitHub refuses them. Work that needs more runs on the project owner's own machine, in their account, with their sign-in.
- Never ask for a token in the chat or in a file. When a person must give access, they sign in on their own machine.
- Ask a person only for what no agent can do: allowing a prompt in their own session, a physical device, adding a machine to the Swarm, approving a repository for the GitHub App, a decision. One step at a time, with the exact words to click or type.
diff --git a/cli/src/superTabs/fixtures/read/index.ts b/cli/src/superTabs/fixtures/read/index.ts
index 26bc70616..74ede84a0 100644
--- a/cli/src/superTabs/fixtures/read/index.ts
+++ b/cli/src/superTabs/fixtures/read/index.ts
@@ -45,14 +45,13 @@ export function hostForm(rows: unknown, options: { tabs?: string[]; pools?: unkn
export function partsOf(state: Json, options: { githubApp?: boolean; lastChangedAt?: number } = {}): Json {
const v = ++version
const part = (key: unknown, data: Json) => ({ key: String(key), version: v, changedAt: v, data })
- const { people, agents, conversations, machines, starts, otherProjectsWork, mentionsWaiting, mentionsDigest, decisionsDigest, teamAccounts, ...head } = state
+ const { people, agents, conversations, machines, starts, otherProjectsWork, mentionsWaiting, mentionsDigest, decisionsDigest, ...head } = state
return { format: 2, tabId: String(state.id ?? 'tab'), cursor: `tab-${v}`, serverTime: v, lastChangedAt: options.lastChangedAt ?? v, epoch: 1,
...(options.githubApp ? { githubApp: true } : {}),
head: part('head', head), members: asList(people).map(p => part(p.id, p)), agents: asList(agents).map(a => part(a.id, a)),
groups: asList(conversations).map((c, i) => part(c.id ?? `group-${i}`, c)), machines: asList(machines).map(m => part(m.machineId, m)),
starts: asList(starts).map(s => part(s.id, s)), progress: [],
- derived: { ...(otherProjectsWork !== undefined ? { otherProjectsWork } : {}), ...(mentionsWaiting !== undefined ? { mentionsWaiting } : {}), ...(mentionsDigest !== undefined ? { mentionsDigest } : {}), ...(decisionsDigest !== undefined ? { decisionsDigest } : {}),
- ...(teamAccounts === false ? { teamAccounts } : {}) } }
+ derived: { ...(otherProjectsWork !== undefined ? { otherProjectsWork } : {}), ...(mentionsWaiting !== undefined ? { mentionsWaiting } : {}), ...(mentionsDigest !== undefined ? { mentionsDigest } : {}), ...(decisionsDigest !== undefined ? { decisionsDigest } : {}) } }
}
/** A fake Swarm read: a changes read asks for a reload, so every read is a first load of the state the test holds now (a
diff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.ts
index a80b6edab..88efba834 100644
--- a/cli/src/superTabs/inCore.ts
+++ b/cli/src/superTabs/inCore.ts
@@ -20,6 +20,8 @@ export { createSwarmAgents } from './inCore/agents.js'
export { SWARM_LAUNCH } from './inCore/launch.js'
export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor, teamPurgeReport, withPurgeRetries } from './inCore/teamApps.js'
export { typesWhileBusy } from './inCore/deliveries.js'
+export { teamRetirement } from './inCore/teamRetire.js'
+export { isTeamAccount } from '../team/config.js'
export { mayBeBuddy, retainedHarnesses, retainedLeads, retainedSleepingBuddies } from './retention.js'
export { recordCleanupClose } from './cleanupCloses.js'
// A Product Manager switched from its pane (Change agent) is the one stop of a Lead its close guard and stop guard let through.
diff --git a/cli/src/superTabs/inCore/teamRetire.spec.ts b/cli/src/superTabs/inCore/teamRetire.spec.ts
new file mode 100644
index 000000000..b0230e3e8
--- /dev/null
+++ b/cli/src/superTabs/inCore/teamRetire.spec.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from 'vitest'
+import { TEAM_RETIRED, teamRetirement } from './teamRetire.js'
+
+// Swarm v3 has no Team accounts (#4221): a Team account's daemon stops for good once no agent runs in it.
+describe('a Harness Team account\'s daemon, after each pass over its agents', () => {
+ const made = (teamAccount: boolean, live: number[]) => {
+ const stop = vi.fn<(reason: string) => void>()
+ const log = vi.fn<(line: string) => void>()
+ const counts = [...live]
+ const pass = teamRetirement({ teamAccount, live: () => counts.shift() ?? 0, stop, log })
+ return { pass, stop, log }
+ }
+
+ it('stops for good, once, when no agent runs in it', () => {
+ const { pass, stop, log } = made(true, [0, 0])
+ pass()
+ pass()
+ expect(stop).toHaveBeenCalledOnce()
+ expect(stop).toHaveBeenCalledWith(TEAM_RETIRED)
+ expect(log).toHaveBeenCalledWith('[team] Swarm v3 has no Team accounts: no agent runs here, stopping for good')
+ })
+
+ it('waits while an agent still runs in it, and stops once the last one is gone', () => {
+ const { pass, stop } = made(true, [2, 1, 0])
+ pass()
+ pass()
+ expect(stop).not.toHaveBeenCalled()
+ pass()
+ expect(stop).toHaveBeenCalledOnce()
+ })
+
+ it('never stops a daemon that is not a Team account\'s: the owner\'s own, or a computer signed in with harness team on', () => {
+ const { pass, stop, log } = made(false, [0])
+ pass()
+ expect(stop).not.toHaveBeenCalled()
+ expect(log).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/superTabs/inCore/teamRetire.ts b/cli/src/superTabs/inCore/teamRetire.ts
new file mode 100644
index 000000000..6976ffd3e
--- /dev/null
+++ b/cli/src/superTabs/inCore/teamRetire.ts
@@ -0,0 +1,20 @@
+/**
+ * Swarm v3 has no Team accounts (anh Dee, 2026-11-07; #4221). A Mac, Linux or Windows computer set up before keeps the
+ * Team account's daemon, which its system starts at every boot. Its files are root's, and removing them needs an
+ * administrator prompt nobody asked for, so the daemon stops itself for good instead: after a pass over its agents finds
+ * none running, so the agents still there finish what they hold first (#4120). At the next boot it starts, finds none and
+ * stops again. `harness team remove` deletes the account, its home and its daemon when its owner chooses.
+ */
+export const TEAM_RETIRED = 'retired'
+
+/** What runs after each pass over this daemon's agents. Only a Team account's daemon (team/config.ts `isTeamAccount`)
+ * ever stops; a computer signed in with `harness team on` is the owner's own daemon and is not one. */
+export function teamRetirement(deps: { teamAccount: boolean; live: () => number; stop: (reason: string) => void; log: (line: string) => void }): () => void {
+ let stopped = !deps.teamAccount
+ return () => {
+ if (stopped || deps.live() > 0) return
+ stopped = true
+ deps.log('[team] Swarm v3 has no Team accounts: no agent runs here, stopping for good')
+ deps.stop(TEAM_RETIRED)
+ }
+}
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 9ac54fe9a..2bb3a7b40 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -706,7 +706,7 @@ export class ContributedMachines {
if (privacy?.mode === 'account' && !privacy.passed && !start.dispatched) {
await scoped({ action: 'command', operationId: `privacy-failed-${start.id}`,
command: { type: 'agent.startFailed', startId: start.id,
- error: `This computer's Harness Team account is not private (${privacy.item}): ${privacy.detail} Its owner can run \`harness team setup\` to repair it.` } })
+ error: `This computer's Harness Team account is not private (${privacy.item}): ${privacy.detail} Its owner can remove it: \`harness team remove\`.` } })
continue
}
// Another person's project is cloned and fetched with the Harness GitHub App's token, never this machine's own
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index ec2ca12d0..6bab40cfc 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto'
-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, readdirSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -7,15 +7,14 @@ import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import type { CoreApi } from '../core/api.js'
import type { SaidOnCard } from './cards.js'
-import { sharedSwarm, superTabService } from './service.js'
+import { superTabService } from './service.js'
import { object } from './wire.js'
import { hostForm, swarmReply } from './fixtures/read/index.js'
import { HostFeed } from './hostFeed.js'
-import { SwarmReads } from './swarmReads.js'
import { CHEAP_FIRST_HELP, GRID_KINDS, MAX_OWNED, ROUTE_KIND_HELP } from './routeCheapFirst.js'
const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
-import { hostJournalFile, SuperTabHostError, type SuperTabHost, type SuperTabHostOptions } from './host.js'
+import { SuperTabHostError, type SuperTabHost, type SuperTabHostOptions } from './host.js'
const owner = { local: true, owner: true }, visitor = { local: false, owner: false }
/** The backend's Lead rule: an agent leads a project when it leads that project's Lead conversation ('lead' before projects). */
@@ -1189,190 +1188,22 @@ describe('the Harness Team account\'s own tmux', () => {
})
})
-describe('the Harness Team account, offered by Desktop on this Mac', () => {
- it('runs only for the local owner, for a moment the person is there, and says whether it started', async () => {
- const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'started' as const }))
- const make = vi.fn(async () => ({ offer, decline: vi.fn() }))
- const service = superTabService(fakeCore(), { teamSetup: make })
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toEqual({ ok: true, state: 'started' })
- expect(offer).toHaveBeenCalledWith('join', expect.any(Function), false, { signInAgain: false })
- for (const asker of [visitor, { local: false, owner: true, accountOwner: true }]) {
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
- }
- for (const reason of [undefined, 'background', 7]) {
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason }, owner)).toEqual({ error: 'INVALID_REQUEST' })
- }
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'contribute' }, owner)
- expect(make).toHaveBeenCalledTimes(1)
- expect(offer).toHaveBeenCalledTimes(2)
- })
-
- it("signs the account in again only when the person's own Set up asks, where it serves another account (#3122)", async () => {
- const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'started' as const }))
- const service = superTabService(fakeCore(), { teamSetup: vi.fn(async () => ({ offer, decline: vi.fn() })) })
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', signInAgain: true }, owner)
- expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: true })
- // Only Set up itself: a check, an automatic moment or anything but true signs nothing in again.
- await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'manual', signInAgain: true }, owner)
- expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), true, { signInAgain: false })
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'join', signInAgain: true }, owner)
- expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), false, { signInAgain: false })
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', signInAgain: 'yes' }, owner)
- 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('allows Team restart only from its local owner and only for a manual setup request', async () => {
- const offer = vi.fn(async () => ({ state: 'started' as const }))
- const service = superTabService(fakeCore(), { teamSetup: vi.fn(async () => ({ offer, decline: vi.fn() })) })
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', restart: true }, owner)
- expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: false, restart: true })
- for (const asker of [{ local: false, owner: true }, { local: true, owner: false }]) {
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', restart: true }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
- }
- expect(offer).toHaveBeenCalledTimes(1)
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'join', restart: true }, owner)
- expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), false, { signInAgain: false })
- })
-
- 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' })
+describe('a Harness Team account, which Swarm v3 has none of (#4221)', () => {
+ it('is offered at no moment, set up, declined or read by this daemon, even where the Swarm cannot be read', async () => {
+ // What a daemon from before would make the setup with: nothing may reach it now.
+ const make = vi.fn(async () => ({ offer: vi.fn(async () => ({ state: 'wanted' as const })), decline: vi.fn(), status: vi.fn() }))
+ const backend = vi.fn<CoreApi['account']['backend']>(async () => ({ status: 503, body: { success: false } }))
+ const service = superTabService(fakeCore({ account: { backend } }), { teamSetup: make } as never)
+ for (const reason of ['startup', 'join', 'contribute', 'manual']) {
+ for (const action of ['teamSetupCheck', 'teamSetup']) {
+ expect(await service.requests.super_tabs({ action, reason, tabId: 'unreadable' }, owner)).toEqual({ error: 'INVALID_REQUEST' })
+ }
}
- 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' }))
- const service = superTabService(fakeCore(), { teamSetup: async () => ({ offer, decline: vi.fn(), status }) })
- expect(await service.requests.super_tabs({ action: 'teamSetupStatus' }, owner)).toEqual({ ok: true, state: 'failed', detail: 'launchd would not start it' })
- // Through the relay, or anyone but the owner: the reason can name this Mac's own setup, so it stays on this Mac.
- for (const asker of [visitor, { local: false, owner: true, accountOwner: true }]) {
- expect(await service.requests.super_tabs({ action: 'teamSetupStatus' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
+ for (const action of ['teamSetupDecline', 'teamSetupStatus']) {
+ expect(await service.requests.super_tabs({ action }, owner)).toEqual({ error: 'INVALID_REQUEST' })
}
- expect(status).toHaveBeenCalledOnce()
- expect(offer).not.toHaveBeenCalled()
- })
-
- it('at app start, answers at once on a Mac that hosts no Swarm work, as no regular user\'s does', async () => {
- const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'not-shared' as const }))
- const make = vi.fn(async () => ({ offer, decline: vi.fn() }))
- const dataDir = mkdtempSync(join(tmpdir(), 'team-startup-'))
- const service = superTabService(fakeCore({ dataDir }), { teamSetup: make })
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'startup' }, owner)).toEqual({ ok: true, state: 'not-shared' })
expect(make).not.toHaveBeenCalled()
- // Once this Mac hosts Swarm work, the offer decides.
- mkdirSync(dirname(hostJournalFile(dataDir, 'machine-1')), { recursive: true })
- writeFileSync(hostJournalFile(dataDir, 'machine-1'), '{}')
- await service.requests.super_tabs({ action: 'teamSetup', reason: 'startup' }, owner)
- expect(offer).toHaveBeenCalledWith('startup', expect.any(Function), false, { signInAgain: false })
- })
-
- it('says whether it is wanted without asking macOS, runs it when the person asks, and remembers "Not now"', async () => {
- const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>, check?: boolean) => ({ state: check ? 'wanted' as const : 'started' as const }))
- const decline = vi.fn()
- const service = superTabService(fakeCore(), { teamSetup: async () => ({ offer, decline }) })
- expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'join' }, owner)).toEqual({ ok: true, state: 'wanted' })
- expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), true, { signInAgain: false })
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual' }, owner)).toEqual({ ok: true, state: 'started' })
- expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: false })
- expect(await service.requests.super_tabs({ action: 'teamSetupDecline' }, owner)).toEqual({ ok: true })
- expect(decline).toHaveBeenCalledOnce()
- for (const action of ['teamSetupCheck', 'teamSetupDecline']) {
- expect(await service.requests.super_tabs({ action, reason: 'join' }, visitor)).toEqual({ error: 'OWNER_REQUIRED' })
- }
- expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'later' }, owner)).toEqual({ error: 'INVALID_REQUEST' })
- })
-
- it('offers nothing for a Swarm joined or added to that the team account is not tried in yet', async () => {
- const offer = vi.fn(async () => ({ state: 'wanted' as const }))
- const tabs: Record<string, Record<string, unknown>> = { elsewhere: { people: [{ id: 'me' }], teamAccounts: false }, mine: { people: [{ id: 'me' }] } }
- const backend = vi.fn<CoreApi['account']['backend']>(async (_method, path) => {
- const tab = tabs[path.split('/')[3]!]
- return tab ? { status: 200, body: { success: true, data: swarmReply(path, tab) } } : { status: 503, body: { success: false } }
- })
- const service = superTabService(fakeCore({ account: { backend } }), { teamSetup: async () => ({ offer, decline: vi.fn() }) })
- for (const reason of ['join', 'contribute']) {
- expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason, tabId: 'elsewhere' }, owner)).toEqual({ ok: true, state: 'not-used' })
- }
- expect(offer).not.toHaveBeenCalled()
- // Its own Swarm, one the server cannot read now, and an older Desktop that names none are offered, as before.
- for (const tabId of ['mine', 'unreadable', undefined]) {
- expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'join', tabId }, owner)).toEqual({ ok: true, state: 'wanted' })
- }
- expect(offer).toHaveBeenCalledTimes(3)
- })
-
- it('tries again to make its setup when making it failed', async () => {
- const make = vi.fn().mockRejectedValueOnce(new Error('import failed')).mockResolvedValueOnce({ offer: async () => ({ state: 'exists' }), decline: vi.fn() })
- const service = superTabService(fakeCore(), { teamSetup: make })
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toMatchObject({ error: 'SUPER_TAB_UNAVAILABLE' })
- expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toEqual({ ok: true, state: 'exists' })
- })
-
- it('at app start, counts a Swarm this Mac is in with anyone else in it', async () => {
- const answers = (pools: unknown, tabs: Record<string, unknown>) => vi.fn<CoreApi['account']['backend']>(async (_method, path) => {
- if (path.includes('/hosts/')) return pools instanceof Error ? { status: 503, body: { success: false } }
- : { status: 200, body: { success: true, data: Array.isArray(pools) ? hostForm([], { pools }) : pools } }
- const tab = tabs[path.split('/')[3]!]
- return tab ? { status: 200, body: { success: true, data: swarmReply(path, tab as Record<string, unknown>) } } : { status: 403, body: { success: false, error: { code: 'FORBIDDEN' } } }
- })
- const sources = (call: CoreApi['account']['backend'], machineId = 'machine-1') => {
- const core = fakeCore({ account: { backend: call }, daemon: { machineId: () => machineId } as never })
- return { feed: new HostFeed(core, machineId), reads: new SwarmReads(core) }
- }
- const shared = answers([{ tabId: 'solo' }, { tabId: 'gone' }, { tabId: 'team' }],
- { solo: { people: [{ id: 'me' }] }, team: { people: [{ id: 'me' }, { id: 'kim' }] } })
- expect(await sharedSwarm(sources(shared))).toBe(true)
- // A Swarm the team account is not tried in yet (backend machines.ts teamAccountSwarm) does not count.
- expect(await sharedSwarm(sources(answers([{ tabId: 'team' }], { team: { people: [{ id: 'me' }, { id: 'kim' }], teamAccounts: false } })))).toBe(false)
- expect(shared.mock.calls.map(c => c[1])).toEqual(['/api/super-tabs/hosts/machine-1/changes?full=1',
- '/api/super-tabs/solo/parts', '/api/super-tabs/gone/parts', '/api/super-tabs/team/parts'])
- expect(await sharedSwarm(sources(answers([{ tabId: 'solo' }, { tabId: '../x' }], { solo: { people: [{ id: 'me' }] } })))).toBe(false)
- expect(await sharedSwarm(sources(answers(new Error('down'), {})))).toBe(false)
- expect(await sharedSwarm(sources(answers({ not: 'a host form' }, {})))).toBe(false)
- expect(await sharedSwarm(sources(answers([], {}), ''))).toBe(false)
+ expect(backend).not.toHaveBeenCalled()
})
})
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 4718d4099..3ad04108c 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -20,7 +20,6 @@ import { messageIdOf } from './attach.js'
import { cardId, SwarmCards, type CardChat } from './cards.js'
import { GitHubTokenRefresher, githubToken } from './github.js'
import { teamEngineReporter, type TeamEngineReporter } from '../team/engines.js'
-import { AUTO_SETUP_REASONS, realTeamAutoSetup, type AutoSetupReason, type TeamAutoSetup } from '../team/autoSetup.js'
import { readTeamConfig } from '../team/config.js'
import { ensureTeamTmux, TMUX_MANIFEST_URL, tmuxRunsAt, untarGz, type TeamTmuxDeps, type TeamTmuxOutcome } from '../team/tmux.js'
import { downloadVerified } from '../lib/selfUpdate.js'
@@ -158,9 +157,6 @@ const OFF_ROSTER = 'This agent is not on this machine\'s Swarm roster right now.
* quotes (BUDDY_COMMAND_HELP): no stdin anywhere. */
const BUDDY_HELP = { ...HELP, post: `post GROUP TEXT OPERATION_ID ${POST_FLAGS}: ${BUDDY_POST_HELP}${MENTION_HELP}`, command: BUDDY_COMMAND_HELP }
const OTHER_WORK_FIELDS = ['conversationId', 'projectName', 'title', 'owns', 'status', 'agentName', 'pr'] as const
-/** How old a host form a one-off question about this machine's Swarms may take: the host reads one every second. */
-const POOLS_FRESH_MS = 5_000
-
/** Leads see each other's work (spec 2026-10-23): a Lead reads other projects' active work in the backend's fields alone;
* any other agent reads none of it. Nobody reads the Leads conversation, removed on 10-31, even from an older server
@@ -269,26 +265,6 @@ function markAnswered(page: unknown, later: unknown[], agentId: string): unknown
}) }
}
-/** Whether this machine is in a Swarm with other people in it: a contribution of its own to a tab whose people are more
- * than its owner. False when that cannot be read. */
-export async function sharedSwarm(sources: SwarmSources): Promise<boolean> {
- if (!identifier(sources.feed.machineId)) return false
- const pools = await sources.feed.current(POOLS_FRESH_MS).then(read => read.pools, () => [])
- for (const row of pools) {
- if (!identifier(row.tabId)) continue
- // A Swarm Harness Team accounts are not tried in yet (backend machines.ts teamAccountSwarm) asks for none.
- const read = await sources.reads.read(row.tabId).catch(() => null)
- if (read?.teamAccounts && Array.isArray(read.state.people) && read.state.people.length > 1) return true
- }
- return false
-}
-
-/** Whether the Swarm a person just joined or added this Mac to uses Harness Team accounts: false only when its server
- * says it does not, so a read that fails still offers, as before. */
-export async function teamAccountsIn(sources: SwarmSources, tabId: string): Promise<boolean> {
- return sources.reads.read(tabId).then(read => read.teamAccounts, () => true)
-}
-
export interface SuperTabServiceOptions {
prepareContribution?: typeof prepareContribution
setMachineAgents?: typeof setMachineAgents
@@ -301,8 +277,6 @@ export interface SuperTabServiceOptions {
githubTokens?: (core: CoreApi) => Pick<GitHubTokenRefresher, 'start' | 'stop'> & Partial<Pick<GitHubTokenRefresher, 'assigned'>>
/** What reports the Harness Team account's own engines to its owner (team/engines.ts), for a spec. */
teamEngines?: () => Pick<TeamEngineReporter, 'start' | 'stop'>
- /** What sets up the Harness Team account when Desktop asks (team/autoSetup.ts), for a spec. */
- teamSetup?: () => Promise<Pick<TeamAutoSetup, 'offer' | 'decline'> & Partial<Pick<TeamAutoSetup, 'status'>>>
/** Whether this daemon runs team work only (a Harness Team account, `harness team on`), for a spec. */
team?: () => boolean
/** The Harness Team account's own tmux (team/tmux.ts), for a spec. */
@@ -365,7 +339,6 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
const tokens = (options.githubTokens ?? (api => new GitHubTokenRefresher(api, sources)))(core)
// In the Harness Team account only: whether its Claude Code and Codex are installed and signed in, for its owner to read.
const engines = (options.teamEngines ?? teamEngineReporter)()
- let autoSetup: Promise<Pick<TeamAutoSetup, 'offer' | 'decline'> & Partial<Pick<TeamAutoSetup, 'status'>>> | null = null
// In the Harness Team account: a tmux and a gh of its own when it has none it can run (team/tmux.ts, team/gh.ts). Looked
// at as it connects, and a failed install again half an hour later.
const settled = (outcome: string) => outcome === 'present' || outcome === 'installed' || outcome === 'not-team'
@@ -438,13 +411,8 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
if (!asker.local) return { error: 'OWNER_REQUIRED' }
return await githubToken(core, String(payload.harnessId ?? ''), sources())
}
- // Desktop on this Mac, as the person joins a Swarm, adds this Mac to one, or opens the app (team/autoSetup.ts): the
- // Harness Team account, behind macOS's own administrator prompt. Never through the relay, with nobody at this Mac.
- // `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.
+ // row (Amon, #3215: "joining" for good, the reason only in the log). Only a client on this computer asks.
// 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' }
@@ -452,33 +420,6 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
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' }
- const setup = () => autoSetup ??= (options.teamSetup ?? (() => realTeamAutoSetup(core.dataDir, line => console.log(`[team] ${line}`))))()
- .catch(error => { autoSetup = null; throw error })
- if (payload.action === 'teamSetupDecline') { (await setup()).decline(); return { ok: true } }
- if (payload.action === 'teamSetupStatus') {
- const made = await setup()
- return made.status ? { ok: true, ...await made.status() } : { error: 'INVALID_REQUEST' }
- }
- if (!AUTO_SETUP_REASONS.includes(payload.reason as AutoSetupReason)) return { error: 'INVALID_REQUEST' }
- // Desktop asks at every launch. A Mac that hosts no Swarm work, as no regular user's does, answers at once:
- // nothing read, run or asked of the backend.
- if (payload.reason === 'startup' && !(identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId())))) {
- return { ok: true, state: 'not-shared' }
- }
- // Joined or added to a Swarm Harness Team accounts are not tried in yet: nothing asked (2026-10-28). An older
- // Desktop names no Swarm and is offered as before.
- if ((payload.reason === 'join' || payload.reason === 'contribute') && identifier(payload.tabId)
- && !await teamAccountsIn(sources(), payload.tabId)) return { ok: true, state: 'not-used' }
- // `signInAgain`: Set up on a row the Swarm says has no Team account while this Mac has one, so it serves another account
- // (#3122). Only the person's own Set up: a check or an automatic moment signs nothing in again.
- const signInAgain = payload.action === 'teamSetup' && payload.reason === 'manual' && payload.signInAgain === true
- const restart = payload.action === 'teamSetup' && payload.reason === 'manual' && payload.restart === true
- return { ok: true, ...await (await setup()).offer(payload.reason as AutoSetupReason, () => sharedSwarm(sources()),
- payload.action === 'teamSetupCheck', { signInAgain, ...restart ? { restart: true } : {} }) }
- }
if (payload.action === 'swarmRole') {
const grant = await port.swarmRole(String(payload.harnessId ?? ''))
// In the wire's values, which the core reads in either set (inCore/role.ts) and a core from before role kinds in
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index dad5f6630..27ee25a97 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -124,20 +124,25 @@ describe('Swarm permission mode', () => {
: request(type, payload, ms))
expect(await inspectCapacity(await f.open() as never, f.start.request)).toMatchObject({ allowed: true, engine: { installed: true, signedIn: false } })
})
- it.each(['claude', 'codex'] as const)('starts %s in full mode on direct and contributed hosts', async engine => {
+ // Swarm v3 (task #4215): each agent starts with its owner's own settings. A mode an older backend still relays is the
+ // PM's, not the person's, so it is not used either.
+ it.each(['claude', 'codex'] as const)('starts %s with its owner\'s own permission settings on direct and contributed hosts', async engine => {
for (const hostDispatch of [false, true]) {
const f = fixture()
- Object.assign(f.start.request, { engine, permissionMode: 'ask' })
+ Object.assign(f.start.request, { engine, permissionMode: 'full' })
if (hostDispatch) Object.assign(f.start, { poolGeneration: 'pool' })
const result = await startAgent({ action: 'resume', tabId: 'tab', startId: 'start', hostDispatch }, f.scoped, where, f.open)
expect(result).toMatchObject({ ok: true })
const payload = f.request.mock.calls.find(c => c[0] === 'agent_create')![1]!
- expect(payload).toMatchObject({ permissionMode: 'full', bypassPermission: true, swarmRole: 'dev' })
+ expect(payload).toMatchObject({ bypassPermission: false, swarmRole: 'dev' })
+ expect(payload).not.toHaveProperty('permissionMode')
// On Windows a launch first verifies the flags the engine's startup takes (lib/windows/engineStart.ts); given here as a
// verified launch gives them, so this reads the permission flags alone (Window of Tim, #3815).
- const argv = buildEngineCommandArgv(engine, { permissionMode: String(payload.permissionMode),
+ const argv = buildEngineCommandArgv(engine, { bypassPermission: payload.bypassPermission as boolean,
...(process.platform === 'win32' ? { native: { startupArgs: [] } as never } : {}) })
- expect(argv).toContain(engine === 'claude' ? '--dangerously-skip-permissions' : '--dangerously-bypass-approvals-and-sandbox')
+ for (const flag of ['--dangerously-skip-permissions', '--dangerously-bypass-approvals-and-sandbox', '--permission-mode', '--ask-for-approval', '--sandbox']) {
+ expect(argv).not.toContain(flag)
+ }
}
})
@@ -265,7 +270,8 @@ describe('Swarm permission mode', () => {
const result = await heavyStart(f, () => undefined)
expect(result).toMatchObject({ ok: true, queued: true, startId: 'start' })
expect(result).not.toHaveProperty('heavyWarning')
- expect(submitted(f)).toEqual([expect.objectContaining({ heavy: ['build'], permissionMode: 'full' })])
+ expect(submitted(f)).toEqual([expect.objectContaining({ heavy: ['build'] })])
+ expect(submitted(f)[0]).not.toHaveProperty('permissionMode')
})
it('sends the start once more without it when an older server refuses that field, and says routes will not count it', async () => {
const f = fixture()
@@ -274,7 +280,8 @@ describe('Swarm permission mode', () => {
const sent = submitted(f)
expect(sent).toHaveLength(2)
expect(sent[1]).not.toHaveProperty('heavy')
- expect(sent[1]).toEqual({ ...sent[0], heavy: undefined, permissionMode: 'full' } as never)
+ expect(sent[1]).toEqual({ ...sent[0], heavy: undefined } as never)
+ expect(sent[1]).not.toHaveProperty('permissionMode')
expect(new Set(f.scoped.mock.calls.filter(c => (c[0].command as { type?: string } | undefined)?.type === 'agent.start').map(c => c[0].operationId))).toEqual(new Set(['op-heavy']))
})
it('never sends it again on a timeout or any other refusal, which may have started an agent', async () => {
@@ -297,26 +304,6 @@ describe('Swarm permission mode', () => {
})
})
- it('recovers the same legacy start after its accepted reply is lost', async () => {
- const f = fixture(), scoped = f.scoped.getMockImplementation()!
- Object.assign(f.start, { poolGeneration: 'pool' })
- let recorded: string | undefined, accepted = 0
- f.scoped.mockImplementation(async payload => {
- const command = payload.command as Record<string, any> | undefined
- if (command?.type !== 'agent.start') return scoped(payload)
- const hash = JSON.stringify(command)
- if (recorded) return recorded === hash ? scoped(payload) : { error: 'OPERATION_REUSED', detail: 'Use a new operation ID for a different request.' }
- if (command.request.permissionMode) return { error: 'OUTSIDE_CONTRIBUTION', detail: 'Refused: permissionMode (it runs with its own default account settings, so leave it out).' }
- recorded = hash; accepted++
- throw new Error('Accepted reply lost')
- })
- const input = { action: 'start', tabId: 'tab', operationId: 'same-op', request: f.start.request }
- await expect(startAgent(input, f.scoped, where, f.open)).rejects.toThrow('Accepted reply lost')
- expect(await startAgent(input, f.scoped, where, f.open, noPause)).toMatchObject({ ok: true, queued: true, startId: 'start' })
- expect(accepted).toBe(1)
- expect(f.open).not.toHaveBeenCalled()
- })
-
it('tells the Lead a contributed start is still being prepared on its machine, so it waits rather than starting another', async () => {
const f = fixture()
Object.assign(f.start, { poolGeneration: 'pool', dispatched: true, preparing: true })
@@ -330,44 +317,13 @@ describe('Swarm permission mode', () => {
expect(f.open).not.toHaveBeenCalled()
})
- it('asks the backend for full mode even when the caller asks for another mode', async () => {
- const f = fixture()
- await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: { ...f.start.request, permissionMode: 'ask' } }, f.scoped, where, f.open)
- const command = f.scoped.mock.calls[0]![0].command as Record<string, any>
- expect(command.request.permissionMode).toBe('full')
- })
-
- it.each([false, true])('recovers an older CLI start without warning that the backend is old (settled=%s)', async settled => {
- const f = fixture()
- Object.assign(f.start, { poolGeneration: 'pool', ...(settled ? { harnessId: 'existing', poolSettled: true } : {}) })
- f.scoped.mockResolvedValueOnce({ error: 'OPERATION_REUSED', detail: 'Use a new operation ID for a different request.' })
- const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'same-op', request: f.start.request }, f.scoped, where, f.open, noPause)
- expect(result).toMatchObject({ ok: true, ...(settled ? { harnessId: 'existing' } : { queued: true }) })
- expect(result).not.toHaveProperty('permissionWarning')
- const attempts = f.scoped.mock.calls.map(c => c[0]).filter(c => (c.command as any)?.type === 'agent.start')
- expect(attempts).toHaveLength(2)
- expect(attempts.map(a => a.operationId)).toEqual(['same-op', 'same-op'])
- expect(f.open).not.toHaveBeenCalled()
- })
-
- it.each([false, true])('retries an older backend permission refusal once and warns (settled=%s)', async settled => {
- const f = fixture(), scoped = f.scoped.getMockImplementation()!
- Object.assign(f.start, { poolGeneration: 'pool', ...(settled ? { harnessId: 'existing', poolSettled: true } : {}) })
- f.scoped.mockImplementation(async payload => {
- const command = payload.command as Record<string, any> | undefined
- if (command?.type === 'agent.start' && command.request.permissionMode) return {
- error: 'OUTSIDE_CONTRIBUTION', detail: 'Studio Mac accepts only its contributed project folder, engines and default account settings. Refused: permissionMode (it runs with its own default account settings, so leave it out).',
- }
- return scoped(payload)
- })
- const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'same-op', request: f.start.request }, f.scoped, where, f.open, noPause)
- expect(result).toMatchObject({ ok: true, ...(settled ? { harnessId: 'existing' } : { queued: true }), permissionWarning: expect.stringContaining("machine's default") })
- const attempts = f.scoped.mock.calls.map(c => c[0]).filter(c => (c.command as any)?.type === 'agent.start')
- expect(attempts).toHaveLength(2)
- expect(attempts.map(a => a.operationId)).toEqual(['same-op', 'same-op'])
- expect((attempts[0]!.command as any).request.permissionMode).toBe('full')
- expect((attempts[1]!.command as any).request).not.toHaveProperty('permissionMode')
- expect(f.open).not.toHaveBeenCalled()
+ it('asks the backend for no permission mode, even when the caller names one', async () => {
+ for (const permissionMode of [undefined, 'ask', 'full']) {
+ const f = fixture()
+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: { ...f.start.request, ...(permissionMode ? { permissionMode } : {}) } }, f.scoped, where, f.open)
+ const command = f.scoped.mock.calls[0]![0].command as Record<string, any>
+ expect(command.request).not.toHaveProperty('permissionMode')
+ }
})
it('does not retry an uncertain backend reply', async () => {
@@ -377,15 +333,6 @@ describe('Swarm permission mode', () => {
expect(f.open).not.toHaveBeenCalled()
})
- it('ends after the single legacy retry fails', async () => {
- const f = fixture()
- f.scoped.mockResolvedValueOnce({ error: 'OUTSIDE_CONTRIBUTION', detail: 'Refused: permissionMode (it runs with its own default account settings, so leave it out).' })
- .mockResolvedValueOnce({ error: 'MACHINE_OFFLINE', detail: 'Wait for the machine.' })
- await expect(startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)).rejects.toThrow('Wait for the machine.')
- expect(f.scoped).toHaveBeenCalledTimes(2)
- expect(f.open).not.toHaveBeenCalled()
- })
-
it('reads an existing native receipt without updating its permission mode', async () => {
const f = fixture(), request = f.request.getMockImplementation()!
f.request.mockImplementation(async (type, payload) => type === 'agent_create_status'
@@ -399,6 +346,8 @@ describe('Swarm permission mode', () => {
{ error: 'OUTSIDE_CONTRIBUTION', detail: 'Refused: codexHome, permissionMode (leave them out).' },
{ error: 'OUTSIDE_CONTRIBUTION', detail: 'Refused: cwd (wrong folder); permissionMode (leave it out).' },
{ error: 'FORBIDDEN', detail: 'permissionMode is forbidden' },
+ { error: 'OUTSIDE_CONTRIBUTION', detail: 'Refused: permissionMode (it runs with its own default account settings, so leave it out).' },
+ { error: 'OPERATION_REUSED', detail: 'Use a new operation ID for a different request.' },
])('does not retry an unrelated refusal: $detail', async refusal => {
const f = fixture(); f.scoped.mockResolvedValue(refusal)
await expect(startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)).rejects.toThrow(refusal.detail)
@@ -533,7 +482,7 @@ it('launches a Codex thread session as any Buddy: the guard its refusal stood fo
const result = await startAgent({ ...OWN_HOST, action: 'start', tabId: 'tab', operationId: 'buddy-codex-session', request: f.start.request } as never, f.scoped, where, f.open)
expect(result.error).toBeUndefined()
const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
- expect([payload.engine, payload.permissionMode, payload.bypassPermission]).toEqual(['codex', 'full', true])
+ expect([payload.engine, payload.permissionMode, payload.bypassPermission]).toEqual(['codex', undefined, false])
})
it('starts a plain Buddy for a thread session whose thread is not an id', async () => {
@@ -546,7 +495,7 @@ it('starts a plain Buddy for a thread session whose thread is not an id', async
expect(payload.prompt).not.toContain('--thread')
})
-it('starts a Buddy in full mode, like its owner\'s own session, and never with the GitHub App\'s token (task #2832)', async () => {
+it('starts a Buddy with its owner\'s own permission settings, and never with the GitHub App\'s token (tasks #2832, #4215)', async () => {
for (const engine of ['claude', 'codex'] as const) {
const f = fixture()
f.start.request = { ...f.start.request, engine, buddyOf: { personId: 'peer', generation: 'g' } } as typeof f.start.request
@@ -554,7 +503,7 @@ it('starts a Buddy in full mode, like its owner\'s own session, and never with t
await startAgent({ ...OWN_HOST, action: 'start', tabId: 'tab', operationId: `buddy-${engine}`, request: f.start.request, github: { requester: 'peer' } } as never,
f.scoped, where, f.open)
const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
- expect([engine, payload.permissionMode, payload.bypassPermission, payload.swarmGitHub]).toEqual([engine, 'full', true, undefined])
+ expect([engine, payload.permissionMode, payload.bypassPermission, payload.swarmGitHub]).toEqual([engine, undefined, false, undefined])
expect(payload.prompt).not.toContain('GitHub')
}
})
@@ -1747,7 +1696,7 @@ describe('neutral start prompts', () => {
})
it('keeps the agent_create payload keys unchanged for old machines', async () => {
// The keys this payload carried before roleName existed (worktree fixture); an older machine's launches.ts refuses others.
- const base = ['branchBase', 'branchName', 'bypassPermission', 'creationId', 'engine', 'gitSource', 'name', 'permissionMode', 'projectSource', 'prompt', 'startedBy', 'swarmRole', 'swarmSkillMode']
+ const base = ['branchBase', 'branchName', 'bypassPermission', 'creationId', 'engine', 'gitSource', 'name', 'projectSource', 'prompt', 'startedBy', 'swarmRole', 'swarmSkillMode']
for (const extra of [lead, {}, { role: 'reviewer' }]) {
for (const roleName of [undefined, 'Tester']) {
const { payload } = await starts(extra, roleName)
@@ -1761,7 +1710,7 @@ describe('neutral start prompts', () => {
// Project instructions, phase 4 (decision 1): the CLI's kinds stay inside it this release; an older machine's launches.ts
// takes lead, dev, review and buddy alone, and refuses a key it does not know.
it('sends an older machine only the role values it knows', async () => {
- const keys = ['branchBase', 'branchName', 'bypassPermission', 'creationId', 'engine', 'gitSource', 'name', 'permissionMode', 'projectSource', 'prompt', 'startedBy', 'swarmRole', 'swarmSkillMode']
+ const keys = ['branchBase', 'branchName', 'bypassPermission', 'creationId', 'engine', 'gitSource', 'name', 'projectSource', 'prompt', 'startedBy', 'swarmRole', 'swarmSkillMode']
for (const [extra, roleName, swarmRole] of [[{}, 'Tester', 'dev'], [{}, undefined, 'dev'], [lead, 'Product Manager', 'lead'], [lead, undefined, 'lead'],
[{ role: 'reviewer' }, 'Reviewer', 'review'], [{ role: 'reviewer' }, undefined, 'review'], [{ role: 'builder' }, 'Engineer', 'dev']] as const) {
const { payload } = await starts(extra, roleName)
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index 7ba15788c..c5534ccdd 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -6,8 +6,6 @@ import { randomUUID } from 'node:crypto'
import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
import { admission, quotaOf, type Requirements } from './capacity.js'
import { groupSkillMode, identifier, object } from './host.js'
-import { permissionModeFlags } from '../lib/engineLaunch.js'
-import type { AgentEngine } from '../engines/types.js'
import { isSwarmSkillMode, swarmSkillUse, wireRole, type SwarmSkillMode } from '../lib/swarmSkills.js'
import { isTeamDaemon, pmEngineHome } from './teamDaemon.js'
import { agentFolderFor, prepareAgentFolder, temporaryFolder } from './agentFolder.js'
@@ -248,15 +246,18 @@ export const HEAVY_NOT_RECORDED = 'This server cannot record that the start runs
async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open: typeof openDaemon): Promise<Json> {
let startId = input.startId
let routed: unknown
- let permissionWarning: string | undefined, heavyWarning: string | undefined
+ let heavyWarning: string | undefined
if (input.action === 'start') {
// The routing decision belongs to the command, not to the machine-side request.
const { routeDecisionId, overrideReason, ...request } = object(input.request)
routed = routeDecisionId
const submit = (request: Json) => scoped({ action: 'command', operationId: input.operationId,
command: { type: 'agent.start', request, ...(routeDecisionId ? { routeDecisionId } : {}), ...(overrideReason ? { overrideReason } : {}) } })
- let sent = request
- let reply = await submit({ ...sent, permissionMode: 'full' })
+ // Swarm v3 (task #4215): an agent starts with its owner's own permission settings, so the start names no mode, whatever
+ // the caller sent; the backend refuses one.
+ const { permissionMode: _mode, ...own } = request
+ let sent: Json = own
+ let reply = await submit(sent)
// A backend from before heavy work was recorded refuses that field in its body check, before it records anything: that
// refusal alone sends the start again without it. A timeout or any other refusal may have started an agent, so it never
// does (Lead, 10-31).
@@ -264,19 +265,7 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
const { heavy: _heavy, ...plain } = sent
sent = plain
heavyWarning = HEAVY_NOT_RECORDED
- reply = await submit({ ...sent, permissionMode: 'full' })
- }
- // Older backends refused this field before recording a start. A recorded
- // legacy retry may instead report a hash mismatch after its reply was lost:
- // replay its exact payload with the same operation ID to recover that receipt.
- // Other refusals and uncertain replies never authorize another intent.
- if (reply.error === 'OPERATION_REUSED' || (reply.error === 'OUTSIDE_CONTRIBUTION' && typeof reply.detail === 'string' &&
- reply.detail.endsWith('Refused: permissionMode (it runs with its own default account settings, so leave it out).'))) {
- const { permissionMode: _mode, ...legacyRequest } = sent
- if (reply.error === 'OUTSIDE_CONTRIBUTION') {
- permissionWarning = "This backend cannot request full permissions. Older machine hosts run the agent with the machine's default. Update Harness on the backend and machine."
- }
- reply = await submit(legacyRequest)
+ reply = await submit(sent)
}
const result = requireSuccess(reply)
startId = object(result.result).startId
@@ -294,15 +283,15 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
return { error: 'SWARM_ENGINE', startId, detail }
}
if (start.harnessId && (!start.poolGeneration || start.poolSettled)) return { ok: true, startId, machineId: request.machineId, harnessId: start.harnessId,
- ...(permissionWarning ? { permissionWarning } : {}), ...(heavyWarning ? { heavyWarning } : {}) }
+ ...(heavyWarning ? { heavyWarning } : {}) }
// Contributed capacity is executed by its owner. A collaborator receives no
// machine credentials and cannot issue arbitrary commands to that computer.
// Its machine reports it preparing (backend liveness.ts): the backend waits up to 15 minutes, and so should the Lead.
if (start.poolGeneration && input.hostDispatch !== true) return start.preparing === true
- ? { ok: true, queued: true, preparing: true, startId, machineId: request.machineId, ...(permissionWarning ? { permissionWarning } : {}), ...(heavyWarning ? { heavyWarning } : {}),
+ ? { ok: true, queued: true, preparing: true, startId, machineId: request.machineId, ...(heavyWarning ? { heavyWarning } : {}),
detail: 'Its machine is still preparing it (fetching the project, checking its worktree out); that can take up to 15 minutes. Resume this start ID to read its receipt; do not start another.' }
: { ok: true, queued: true, startId, machineId: request.machineId,
- ...(permissionWarning ? { permissionWarning } : {}), ...(heavyWarning ? { heavyWarning } : {}),
+ ...(heavyWarning ? { heavyWarning } : {}),
detail: 'Queued on the contributed machine. Resume this start ID to read its receipt.' }
const target = await open(where, request.machineId)
/** What the agent runs now, and its frame, as the frame says; null when the frame cannot say. */
@@ -450,13 +439,17 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
const hosted = input.hostDispatch === true ? object(input.github) : null
const facts = skilled && !hosted ? await projectFacts(scoped, request.conversationId, start.machineOwnerId) : null
const mode = !skilled ? null : isSwarmSkillMode(start.skillMode) ? start.skillMode : facts?.mode ?? 'orchestration'
- // A Buddy is its owner's right hand (Ken, 11-04, task #2832): on their own machine it launches like their own session, in
- // full mode, and uses their own git and gh. It never gets the Harness GitHub App's token, which is for a task's agents.
+ // A Buddy is its owner's right hand (Ken, 11-04, task #2832): on their own machine it launches like their own session and
+ // uses their own git and gh. It never gets the Harness GitHub App's token, which is for a task's agents.
const github = buddy ? null : hosted ? (typeof hosted.requester === 'string' && hosted.requester ? { requester: hosted.requester } : null) : facts?.github ?? null
// The role's name from the project's document, when the backend's start request has it; one line, bounded.
const roleName = typeof request.roleName === 'string' ? request.roleName.replace(/\s+/g, ' ').trim().slice(0, 80) : ''
- const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: true,
- ...(projectSettingsOff ? { permissionMode: 'teamWritten' } : permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
+ // Swarm v3 (task #4215): a PM, an agent and a Buddy start with their owner's own permission settings: no mode, so the
+ // engine opens in the person's own default. Forced full mode turned off every check on people's own computers, where
+ // Anthropic says to use it only in isolated environments. Team-written work keeps its barrier against the branch's own
+ // settings, in a Team home that is no person's.
+ const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: projectSettingsOff,
+ ...(projectSettingsOff ? { permissionMode: 'teamWritten' } : {}),
...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),
...(github ? { swarmGitHub: true } : {}),
// A thread session (#2345) gets its own Buddy note; a coordinator's and an agent's notes name their role (phase 3).
@@ -663,6 +656,6 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
engineVersion: text(last.frame.engineVersion)?.slice(0, 160) ?? null } : null
return { ok: true, startId, machineId: request.machineId, harnessId: nativeId, ...object(joined.result),
...(settledConfiguration ? { configuration: settledConfiguration } : {}),
- ...(permissionWarning ? { permissionWarning } : {}), ...(heavyWarning ? { heavyWarning } : {}), ...(modelWarning ? { modelWarning } : {}) }
+ ...(heavyWarning ? { heavyWarning } : {}), ...(modelWarning ? { modelWarning } : {}) }
} finally { target.close() }
}
diff --git a/cli/src/superTabs/swarmReads.spec.ts b/cli/src/superTabs/swarmReads.spec.ts
index 577572944..42b9e94ed 100644
--- a/cli/src/superTabs/swarmReads.spec.ts
+++ b/cli/src/superTabs/swarmReads.spec.ts
@@ -27,7 +27,7 @@ describe('the daemon\'s Swarm reads', () => {
it('first loads a Swarm once as the agent, then reads only what changed', async () => {
const { call, reads } = backendOf({ [FIRST]: [ok(readFixture('parts-lead'))], [CHANGES()]: [ok(readFixture('changes-lead'))] })
const first = await reads.read(T, LEAD)
- expect(first).toEqual({ state: readFixture<{ state: Json }>('legacy-tab-lead').state, lastChangedAt: 1793010101002, githubApp: true, steps: false, teamAccounts: true,
+ expect(first).toEqual({ state: readFixture<{ state: Json }>('legacy-tab-lead').state, lastChangedAt: 1793010101002, githubApp: true, steps: false,
groupChangedAt: new Map([['c00000000000000000000001', 1793010000000], ['c00000000000000000000000', 1793009000000],
['c00000000000000000000002', 1793010101002], ['c00000000000000000000003', 1793009500000]]) })
const next = await reads.read(T, LEAD)
diff --git a/cli/src/superTabs/swarmReads.ts b/cli/src/superTabs/swarmReads.ts
index c83f3b0d7..bfc647102 100644
--- a/cli/src/superTabs/swarmReads.ts
+++ b/cli/src/superTabs/swarmReads.ts
@@ -11,9 +11,7 @@ import { backend, object, readable, SuperTabHostError } from './wire.js'
type Json = Record<string, unknown>
/** A Swarm as `GET /api/super-tabs/:id` gave it: its state in the old shape, `lastChangedAt` in place of `revision`. */
-/** `teamAccounts`: whether Harness Team accounts are used in this Swarm; false only where its server says they are not tried
- * yet, so an older server's Swarm reads true. */
-export interface SwarmRead { state: Json; lastChangedAt: number | null; githubApp: boolean; steps?: boolean; teamAccounts: boolean
+export interface SwarmRead { state: Json; lastChangedAt: number | null; githubApp: boolean; steps?: boolean
/** When each active group last changed, from its part: what a Buddy's summary marks as new since its last read. */
groupChangedAt: ReadonlyMap<string, number> }
@@ -65,6 +63,6 @@ export class SwarmReads {
this.held.delete(oldest)
}
const groupChangedAt = new Map([...store.parts.get('group')?.values() ?? []].map(part => [part.key, part.changedAt]))
- return { state: reassemble(store), lastChangedAt: store.lastChangedAt, githubApp: store.githubApp, steps: store.steps === true, teamAccounts: store.derived.teamAccounts !== false, groupChangedAt }
+ return { state: reassemble(store), lastChangedAt: store.lastChangedAt, githubApp: store.githubApp, steps: store.steps === true, groupChangedAt }
}
}
diff --git a/cli/src/team/admin.spec.ts b/cli/src/team/admin.spec.ts
index d4ea93393..700b3ab55 100644
--- a/cli/src/team/admin.spec.ts
+++ b/cli/src/team/admin.spec.ts
@@ -150,7 +150,7 @@ describe('adminRunner', () => {
it('without a desktop session, answers that it needs a terminal and runs nothing', async () => {
const f = linux({ code: 0 }, false)
expect(await f.run(() => ({ script: '' }), 'p'))
- .toEqual({ ok: false, code: 'NO_PROMPT', message: 'No administrator prompt here: run harness team setup in a terminal.' })
+ .toEqual({ ok: false, code: 'NO_PROMPT', message: 'No administrator prompt here: run the command in a terminal.' })
expect(f.runner).not.toHaveBeenCalled()
expect(existsSync(f.stage)).toBe(false)
})
diff --git a/cli/src/team/admin.ts b/cli/src/team/admin.ts
index 6c26c6af4..b34877230 100644
--- a/cli/src/team/admin.ts
+++ b/cli/src/team/admin.ts
@@ -70,13 +70,13 @@ export function adminPromptShows(env: NodeJS.ProcessEnv = process.env, exists: (
}
/** What a Linux computer with no desktop session answers for the prompt (over SSH, or Desktop's daemon with no display). */
-export const NO_PROMPT_MESSAGE = 'No administrator prompt here: run harness team setup in a terminal.'
+export const NO_PROMPT_MESSAGE = 'No administrator prompt here: run the command in a terminal.'
/**
* Whether pkexec's answer is the person's "no". 126 is a dismissed dialog. 127 is a refused authorization only when pkexec
* says so: it is also no authentication agent to ask with (pkexec 124 with no session: "Error creating textual
- * authentication agent", gridtest VM, 2026-10-28) and a command the script could not find. Those are failures; read as a
- * cancel, Desktop's offer would remember a "no" nobody gave, for good (./autoSetup.ts).
+ * authentication agent", gridtest VM, 2026-10-28) and a command the script could not find. Those are failures, not the person's
+ * answer.
*/
function pkexecCancelled(code: number | null, stderr: string): boolean {
if (code === 126) return true
diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.ts
deleted file mode 100644
index 9ec582aa1..000000000
--- a/cli/src/team/autoSetup.spec.ts
+++ /dev/null
@@ -1,348 +0,0 @@
-import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import type { AuthSession } from '../lib/authSession.js'
-import type { TeamConfig } from './config.js'
-import {
- AUTO_SETUP_RETRY_MS, readTeamSetupDecision, TeamAutoSetup, teamSetupDecisionFile, writeTeamSetupDecision, type AutoSetupDeps, type TeamSetupDecision,
-} from './autoSetup.js'
-
-const session: AuthSession = { version: 1, accessToken: 'access-placeholder', autonomousEnv: 'prod', computerId: 'c'.repeat(32), updatedAt: 1 }
-
-function fake(over: Partial<AutoSetupDeps> = {}) {
- let decision: TeamSetupDecision | null = null
- const log: string[] = []
- const deps: AutoSetupDeps = {
- platform: 'darwin', session: () => session, readConfig: () => null, accountExists: vi.fn(async () => false),
- readDecision: () => decision, writeDecision: vi.fn((d: TeamSetupDecision) => { decision = d }),
- setup: vi.fn(async () => ({ code: 0, result: { ok: true } })), now: () => 1_000_000, log: (line) => log.push(line), ...over,
- }
- return { auto: new TeamAutoSetup(deps), deps, log, decision: () => decision, setDecision: (d: TeamSetupDecision | null) => { decision = d } }
-}
-
-const cleanup: string[] = []
-afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })
-
-describe('the Harness Team account, set up on its own', () => {
- it('starts setup as the person joins or adds this Mac, once at a time, and answers at once', async () => {
- let made = false
- const f = fake({ accountExists: vi.fn(async () => made) })
- let finish: (value: { code: number; result: Record<string, unknown> | null }) => void = () => {}
- ;(f.deps.setup as ReturnType<typeof vi.fn>).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
- expect(await f.auto.offer('join')).toEqual({ state: 'started' })
- expect(await f.auto.offer('contribute')).toEqual({ state: 'running' })
- made = true
- finish({ code: 0, result: { ok: true } })
- await f.auto.settled()
- expect(f.deps.setup).toHaveBeenCalledTimes(1)
- expect(f.deps.writeDecision).not.toHaveBeenCalled()
- expect(f.log.join('\n')).toContain('the Harness Team account is set up')
- })
-
- it('says in its log why it asked nothing, one line per answer, so a Mac that never saw the prompt can tell why', async () => {
- const cases: Array<[Partial<AutoSetupDeps>, string]> = [
- [{ platform: 'freebsd' }, 'unsupported'], [{ session: () => null }, 'signed-out'], [{ session: () => ({ ...session, kind: 'team' }) }, 'dedicated'],
- [{ accountExists: vi.fn(async () => true) }, 'exists'],
- ]
- for (const [over, state] of cases) {
- const f = fake(over)
- await f.auto.offer('startup', async () => true)
- expect(f.log, state).toEqual([`the Harness Team account was not offered (startup): ${state}`])
- }
- const declined = fake()
- declined.setDecision({ state: 'declined', at: 1 })
- await declined.auto.offer('join')
- expect(declined.log).toEqual(['the Harness Team account was not offered (join): declined'])
- const alone = fake()
- await alone.auto.offer('startup', async () => false)
- expect(alone.log).toEqual(['the Harness Team account was not offered (startup): not-shared'])
- })
-
- it('asks nothing off a Mac, signed out, on a computer that runs team work only, or where the account exists', async () => {
- const cases: Array<[Partial<AutoSetupDeps>, string]> = [
- [{ platform: 'freebsd' }, 'unsupported'], [{ session: () => null }, 'signed-out'],
- [{ session: () => ({ ...session, kind: 'team' }) }, 'dedicated'], [{ readConfig: () => ({ user: 'harnessteam' }) as TeamConfig }, 'exists'],
- [{ accountExists: vi.fn(async () => true) }, 'exists'],
- ]
- for (const [over, state] of cases) {
- const f = fake(over)
- expect(await f.auto.offer('join'), state).toEqual({ state })
- expect(f.deps.setup).not.toHaveBeenCalled()
- }
- })
-
- it('remembers a cancelled prompt and does not ask again on its own; a failed setup waits a day', async () => {
- const cancelled = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'CANCELLED', message: 'Nothing was changed' } })) })
- expect(await cancelled.auto.offer('join')).toEqual({ state: 'started' })
- await cancelled.auto.settled()
- expect(cancelled.decision()).toEqual({ state: 'declined', at: 1_000_000 })
- expect(await cancelled.auto.offer('contribute')).toEqual({ state: 'declined' })
- expect(await cancelled.auto.offer('startup', async () => true)).toEqual({ state: 'declined' })
- expect(cancelled.deps.setup).toHaveBeenCalledTimes(1)
-
- let now = 1_000_000
- const failed = fake({ now: () => now, setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'SETUP_FAILED', message: 'launchd would not start it' } })) })
- await failed.auto.offer('join')
- await failed.auto.settled()
- expect(failed.decision()).toEqual({ state: 'failed', at: 1_000_000, detail: 'launchd would not start it' })
- expect(await failed.auto.offer('join')).toEqual({ state: 'waiting' })
- now += AUTO_SETUP_RETRY_MS
- expect(await failed.auto.offer('join')).toEqual({ state: 'started' })
- await failed.auto.settled()
- // A setup that threw is a failure too; one that made the account but whose daemon has not reported is not.
- const threw = fake({ setup: vi.fn(async () => { throw new Error('osascript missing') }) })
- await threw.auto.offer('join'); await threw.auto.settled()
- expect(threw.decision()).toMatchObject({ state: 'failed', detail: 'osascript missing' })
- // The account was made: only the report is late.
- let slowMade = false
- const slow = fake({ setup: vi.fn(async () => { slowMade = true; return { code: 1, result: { ok: false, privacy: null } } }),
- accountExists: vi.fn(async () => slowMade) })
- await slow.auto.offer('join'); await slow.auto.settled()
- expect(slow.decision()).toBeNull()
- expect(slow.log.join('\n')).toContain('harness team status')
- const unreadable = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'CANCELLED' } })),
- writeDecision: vi.fn(() => { throw new Error('read-only') }) })
- await unreadable.auto.offer('join'); await unreadable.auto.settled()
- expect(unreadable.log.join('\n')).toContain('could not remember')
- })
-
- // Scholes, 2026-11-04: a setup that ended without the account, for a reason outside MADE_NOTHING (osascript's
- // 15 minutes, a code this CLI does not know, no answer at all), remembered nothing, so Desktop's status read `none`
- // and its lock could not say why.
- it('remembers why whenever a setup ends without the account, whatever it answered', async () => {
- const cases: Array<[{ code: number; result: Record<string, unknown> | null }, string]> = [
- [{ code: 1, result: { ok: false, code: 'SOMETHING_NEW', message: 'The script stopped (exit null).' } }, 'The script stopped (exit null).'],
- [{ code: 1, result: { ok: false, privacy: null } }, 'Setup ended (exit 1) without making the Harness Team account.'],
- [{ code: 1, result: null }, 'Setup ended (exit 1) without making the Harness Team account.'],
- [{ code: 0, result: { ok: true } }, 'Setup ended (exit 0) without making the Harness Team account.'],
- ]
- for (const [outcome, detail] of cases) {
- const f = fake({ setup: vi.fn(async () => outcome) })
- await f.auto.offer('join'); await f.auto.settled()
- expect(f.decision(), detail).toMatchObject({ state: 'failed', detail })
- expect(await f.auto.status()).toEqual({ state: 'failed', detail })
- }
- // A cancel is still a no, and an account that is there is no failure.
- const cancelled = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'CANCELLED' } })) })
- await cancelled.auto.offer('join'); await cancelled.auto.settled()
- expect(cancelled.decision()).toMatchObject({ state: 'declined' })
- let made = false
- const ok = fake({ setup: vi.fn(async () => { made = true; return { code: 0, result: { ok: true } } }), accountExists: vi.fn(async () => made) })
- await ok.auto.offer('join'); await ok.auto.settled()
- expect(ok.decision()).toBeNull()
- })
-
- it('says the step a running setup is on and how long it has run, for Desktop\'s waiting screen', async () => {
- let now = 1_000_000
- let step: (name: string) => void = () => {}
- let finish: (value: { code: number; result: Record<string, unknown> | null }) => void = () => {}
- const f = fake({ now: () => now, setup: vi.fn((progress?: (name: string) => void) => {
- step = progress ?? (() => {})
- return new Promise<{ code: number; result: Record<string, unknown> | null }>((resolve) => { finish = resolve })
- }) })
- await f.auto.offer('manual')
- expect(await f.auto.status()).toEqual({ state: 'running', elapsedMs: 0 })
- now += 95_000
- step('engines')
- expect(await f.auto.status()).toEqual({ state: 'running', step: 'engines', elapsedMs: 95_000 })
- finish({ code: 0, result: { ok: true } })
- await f.auto.settled()
- expect((await f.auto.status()).step).toBeUndefined()
- })
-
- it('says in its log when the account was made without Claude Code or Codex, and how to add them', async () => {
- let made = false
- const f = fake({ accountExists: vi.fn(async () => made), setup: vi.fn(async () => {
- made = true
- return { code: 0, result: { ok: true, engines: { checkedAt: 1, claude: { installed: false, signedIn: null }, codex: { installed: true, signedIn: false } } } }
- }) })
- await f.auto.offer('join'); await f.auto.settled()
- expect(f.log.join('\n')).toContain('Claude Code is not installed in the Harness Team account: harness team setup installs it')
- expect(f.decision()).toBeNull()
- })
-
- it('tells its own Desktop why there is no account: cancelled, failed with the reason, still running, or nothing yet', async () => {
- const f = fake()
- expect(await f.auto.status()).toEqual({ state: 'none' })
- f.setDecision({ state: 'declined', at: 5 })
- expect(await f.auto.status()).toEqual({ state: 'declined' })
- f.setDecision({ state: 'failed', at: 5, detail: 'launchd would not start it' })
- expect(await f.auto.status()).toEqual({ state: 'failed', detail: 'launchd would not start it' })
- let finish: (value: { code: number; result: Record<string, unknown> | null }) => void = () => {}
- ;(f.deps.setup as ReturnType<typeof vi.fn>).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
- await f.auto.offer('manual')
- expect(await f.auto.status()).toEqual({ state: 'running', elapsedMs: 0 })
- finish({ code: 0, result: { ok: true } })
- await f.auto.settled()
- // Made since: whatever was remembered before no longer explains anything.
- const made = fake({ accountExists: vi.fn(async () => true) })
- made.setDecision({ state: 'declined', at: 5 })
- expect(await made.auto.status()).toEqual({ state: 'exists' })
- expect(made.deps.setup).not.toHaveBeenCalled()
- })
-
- it('on Linux, offers it as on a Mac: wanted at a join, then started; an account there answers exists', async () => {
- const linux = fake({ platform: 'linux' })
- expect(await linux.auto.offer('join', undefined, true)).toEqual({ state: 'wanted' })
- expect(linux.deps.setup).not.toHaveBeenCalled()
- expect(await linux.auto.offer('manual')).toEqual({ state: 'started' })
- await linux.auto.settled()
- expect(linux.deps.setup).toHaveBeenCalledTimes(1)
- // Its log names the system that asks (the gridtest VM said "macOS" on Linux, 2026-10-28).
- expect(linux.log[0]).toBe('setting up the Harness Team account: the system asks for an administrator password')
- expect(await fake({ platform: 'linux', accountExists: vi.fn(async () => true) }).auto.offer('join')).toEqual({ state: 'exists' })
- // Windows too: User Account Control can always show, while a person is at it (Desktop asks only then).
- expect(await fake({ platform: 'win32', canPrompt: () => false }).auto.offer('join', undefined, true)).toEqual({ state: 'wanted' })
- const windows = fake({ platform: 'win32' })
- expect(await windows.auto.offer('join')).toEqual({ state: 'started' })
- await windows.auto.settled()
- expect(windows.log[0]).toBe('setting up the Harness Team account: Windows asks for permission (User Account Control)')
- expect(await fake({ platform: 'win32', accountExists: vi.fn(async () => true) }).auto.offer('join')).toEqual({ state: 'exists' })
- })
-
- it('on Linux with no prompt it can show, answers no-prompt up front, runs nothing and remembers nothing', async () => {
- // The owner's daemon under systemd --user has no DISPLAY: setup would only answer NO_PROMPT after "started" was said.
- for (const [reason, check] of [['join', true], ['manual', false], ['manual', true]] as const) {
- const f = fake({ platform: 'linux', canPrompt: () => false })
- expect(await f.auto.offer(reason, undefined, check), `${reason} ${check}`).toEqual({ state: 'no-prompt' })
- expect(f.deps.setup).not.toHaveBeenCalled()
- expect(f.deps.writeDecision).not.toHaveBeenCalled()
- expect(f.log).toEqual([`the Harness Team account was not offered (${reason}): no-prompt`])
- }
- // An account that is there, or a Mac (osascript always asks), is answered as before.
- expect(await fake({ platform: 'linux', canPrompt: () => false, accountExists: vi.fn(async () => true) }).auto.offer('manual')).toEqual({ state: 'exists' })
- expect(await fake({ platform: 'darwin', canPrompt: () => false }).auto.offer('join', undefined, true)).toEqual({ state: 'wanted' })
- expect(await fake({ platform: 'linux', canPrompt: () => true }).auto.offer('join', undefined, true)).toEqual({ state: 'wanted' })
- })
-
- it('remembers a setup Linux refused before it made anything as failed: no systemd, no tmux, no prompt to show', async () => {
- for (const code of ['NO_SYSTEMD', 'NO_TMUX', 'NO_PROMPT']) {
- const f = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, code, message: `refused: ${code}` } })) })
- await f.auto.offer('join'); await f.auto.settled()
- expect(f.decision(), code).toEqual({ state: 'failed', at: 1_000_000, detail: `refused: ${code}` })
- }
- })
-
- it('at app start, asks only while this Mac is in a Swarm with other people in it', async () => {
- const alone = fake()
- expect(await alone.auto.offer('startup', async () => false)).toEqual({ state: 'not-shared' })
- expect(await alone.auto.offer('startup')).toEqual({ state: 'not-shared' })
- expect(await alone.auto.offer('startup', async () => { throw new Error('offline') })).toEqual({ state: 'not-shared' })
- expect(alone.deps.setup).not.toHaveBeenCalled()
- const shared = fake()
- expect(await shared.auto.offer('startup', async () => true)).toEqual({ state: 'started' })
- await shared.auto.settled()
- expect(shared.deps.setup).toHaveBeenCalledTimes(1)
- })
-
- it('says it is wanted without asking macOS, so Desktop can explain it first; "Not now" is remembered', async () => {
- const f = fake()
- expect(await f.auto.offer('startup', async () => true, true)).toEqual({ state: 'wanted' })
- expect(await f.auto.offer('startup', async () => false, true)).toEqual({ state: 'not-shared' })
- expect(f.deps.setup).not.toHaveBeenCalled()
- f.auto.decline()
- expect(f.decision()).toEqual({ state: 'declined', at: 1_000_000 })
- expect(await f.auto.offer('join', undefined, true)).toEqual({ state: 'declined' })
- const there = fake({ accountExists: vi.fn(async () => true) })
- expect(await there.auto.offer('manual', undefined, true)).toEqual({ state: 'exists' })
- })
-
- it('runs when the person asks, past a cancel or a failure remembered from before, and alone in a Swarm', async () => {
- const f = fake()
- f.setDecision({ state: 'declined', at: 1 })
- expect(await f.auto.offer('manual', undefined, true)).toEqual({ state: 'wanted' })
- expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
- await f.auto.settled()
- f.setDecision({ state: 'failed', at: 1_000_000 })
- expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
- await f.auto.settled()
- expect(f.deps.setup).toHaveBeenCalledTimes(2)
- })
-
- it('keeps its memory in the daemon\'s own folder, private, and reads nothing it did not write', () => {
- const dir = mkdtempSync(join(tmpdir(), 'team-setup-'))
- cleanup.push(dir)
- const file = teamSetupDecisionFile(dir)
- expect(readTeamSetupDecision(file)).toBeNull()
- writeTeamSetupDecision(file, { state: 'failed', at: 5, detail: 'x'.repeat(400) })
- expect(statSync(file).mode & 0o777).toBe(0o600)
- expect(readTeamSetupDecision(file)).toEqual({ state: 'failed', at: 5, detail: 'x'.repeat(300) })
- writeTeamSetupDecision(file, { state: 'declined', at: 6 })
- expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ state: 'declined', at: 6 })
- writeTeamSetupDecision(file, null)
- expect(readTeamSetupDecision(file)).toBeNull()
- writeTeamSetupDecision(file, null)
- for (const text of ['{', '{"state":"maybe","at":1}', '{"state":"declined","at":"now"}']) {
- writeFileSync(file, text)
- expect(readTeamSetupDecision(file), text).toBeNull()
- }
- })
-})
-
-describe('a half-finished setup is repaired, not taken for done (#2765, Darren-MacBook)', () => {
- it('with the account but no daemon, Set up runs setup again; the automatic moments ask for nothing', async () => {
- const missing = vi.fn(async () => ['daemon'] as const)
- const f = fake({ accountExists: vi.fn(async () => true), missing } as Partial<AutoSetupDeps>)
- for (const reason of ['startup', 'join', 'contribute'] as const) {
- expect(await f.auto.offer(reason, async () => true), reason).toEqual({ state: 'incomplete' })
- }
- expect(f.deps.setup).not.toHaveBeenCalled()
- // Desktop's explanation first, then the person's Set up: the repair runs.
- expect(await f.auto.offer('manual', async () => true, true)).toEqual({ state: 'wanted' })
- expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
- await f.auto.settled()
- expect(f.deps.setup).toHaveBeenCalledTimes(1)
- })
-
- it('a remembered cancel or failure does not stop Set up from repairing', async () => {
- const f = fake({ accountExists: vi.fn(async () => true), missing: async () => ['daemon'] } as Partial<AutoSetupDeps>)
- f.setDecision({ state: 'failed', at: 1_000_000 - 1 })
- expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
- })
-
- it('status names what is missing, for the machine row', async () => {
- const daemon = fake({ accountExists: vi.fn(async () => true), missing: async () => ['daemon'] } as Partial<AutoSetupDeps>)
- expect(await daemon.auto.status()).toEqual({ state: 'incomplete', missing: ['daemon'], detail: 'the team daemon is not running' })
- const privacy = fake({ accountExists: vi.fn(async () => true), missing: async () => ['privacy'] } as Partial<AutoSetupDeps>)
- expect(await privacy.auto.status()).toEqual({ state: 'incomplete', missing: ['privacy'], detail: 'its privacy check has not passed' })
- const both = fake({ accountExists: vi.fn(async () => true), missing: async () => ['daemon', 'privacy'] } as Partial<AutoSetupDeps>)
- expect((await both.auto.status()).detail).toBe('the team daemon is not running, and its privacy check has not passed')
- })
-
- it("with every part in place, signs the account in again for this Mac's account when Set up asks, where it serves another (#3122)", async () => {
- const f = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
- expect(await f.auto.offer('manual', async () => true, false, { signInAgain: true })).toEqual({ state: 'started' })
- await f.auto.settled()
- expect(f.deps.setup).toHaveBeenCalledWith(expect.any(Function), { signInAgain: true })
- // Never on its own: an automatic moment, or Desktop's explanation, asks for no password.
- const quiet = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
- expect(await quiet.auto.offer('join', async () => true, false, { signInAgain: true })).toEqual({ state: 'exists' })
- expect(await quiet.auto.offer('manual', async () => true, true, { signInAgain: true })).toEqual({ state: 'wanted' })
- expect(quiet.deps.setup).not.toHaveBeenCalled()
- })
-
- it('restarts an existing account only on an explicit manual restart and preserves its sign-in', async () => {
- const f = fake({ accountExists: vi.fn(async () => true) })
- expect(await f.auto.offer('join', undefined, false, { restart: true })).toEqual({ state: 'exists' })
- expect(await f.auto.offer('manual', undefined, true, { restart: true })).toEqual({ state: 'wanted' })
- expect(f.deps.setup).not.toHaveBeenCalled()
- expect(await f.auto.offer('manual', undefined, false, { restart: true })).toEqual({ state: 'started' })
- await f.auto.settled()
- expect(f.deps.setup).toHaveBeenCalledWith(expect.any(Function))
- })
-
- it('with every part in place it is done: exists, and nothing runs', async () => {
- const f = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
- expect(await f.auto.offer('manual')).toEqual({ state: 'exists' })
- expect(await f.auto.status()).toEqual({ state: 'exists' })
- expect(f.deps.setup).not.toHaveBeenCalled()
- })
-
- it('a part it cannot read counts as missing, so Set up can still repair it', async () => {
- const f = fake({ accountExists: vi.fn(async () => true), missing: async () => { throw new Error('launchctl timed out') } } as Partial<AutoSetupDeps>)
- expect(await f.auto.status()).toMatchObject({ state: 'incomplete', missing: ['daemon'] })
- expect(await f.auto.offer('manual')).toEqual({ state: 'started' })
- })
-})
-
diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.ts
deleted file mode 100644
index 39465bd8e..000000000
--- a/cli/src/team/autoSetup.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-/**
- * The Harness Team account, set up on its own the moment a person joins a Swarm or adds this Mac to one
- * (docs/plans/2026-10-24-swarm-team-account.md, Task 3). The owner chose "no button, no setup screen": the only thing a
- * person sees is macOS's own administrator prompt, and it appears while they are at this Mac doing that. Desktop asks this
- * Mac's own daemon (super_tabs `teamSetup`, from the local owner only) right after a join or a contribution succeeds;
- * nothing asks from a background event, with nobody there. On Linux the prompt is polkit's, and with no desktop session to
- * show it in the answer is NO_PROMPT: run `harness team setup` in a terminal. On Windows it is User Account Control's,
- * which can always be shown while a person is at the computer, as Desktop asks only then.
- *
- * Macs that joined and were added before this release never pass through either moment, and routing now sends
- * teammates' work only to Team machines. So Desktop also asks once as it starts on a Mac (`startup`), with the person
- * there: it goes ahead only while this Mac is in a Swarm with other people in it.
- *
- * A cancelled prompt is remembered, so the next join does not ask again: only `harness team setup`, run by the person,
- * offers it again. Removing the account (`harness team remove`) is remembered the same way. A setup that failed is not
- * tried again on its own for a day.
- *
- * Desktop explains the account before macOS asks (the prompt is titled "osascript", which read as a surprise on
- * 2026-10-27): it first asks whether the setup is wanted (`check`), shows why, and only then runs it (`manual`), or
- * remembers "Not now" (`decline`). `manual` is also the machine row's Set up button: the person asked, so a cancel or
- * failure remembered from before does not stand in the way.
- */
-import { readFileSync, renameSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'
-import { dirname, join } from 'node:path'
-import type { AuthSession } from '../lib/authSession.js'
-import type { TeamConfig } from './config.js'
-import type { TeamCommandDeps } from './command.js'
-import { TEAM_USER, teamLayout } from './layout.js'
-
-export interface TeamSetupDecision {
- /** `declined`: the person cancelled the prompt or removed the account. `failed`: setup could not make it. */
- state: 'declined' | 'failed'
- at: number
- detail?: string
-}
-
-/** Where the owner's daemon keeps the decision, in its own data folder. */
-export const teamSetupDecisionFile = (dataDir: string) => join(dataDir, 'team-setup.json')
-
-export function readTeamSetupDecision(file: string): TeamSetupDecision | null {
- try {
- const value = JSON.parse(readFileSync(file, 'utf8')) as Partial<TeamSetupDecision>
- if ((value.state !== 'declined' && value.state !== 'failed') || typeof value.at !== 'number' || !Number.isFinite(value.at)) return null
- return { state: value.state, at: value.at, ...(typeof value.detail === 'string' ? { detail: value.detail.slice(0, 300) } : {}) }
- } catch { return null }
-}
-
-export function writeTeamSetupDecision(file: string, decision: TeamSetupDecision | null): void {
- if (!decision) { rmSync(file, { force: true }); return }
- mkdirSync(dirname(file), { recursive: true })
- const next = `${file}.${process.pid}.next`
- writeFileSync(next, `${JSON.stringify(decision)}\n`, { mode: 0o600 })
- renameSync(next, file)
-}
-
-/** A failed setup is offered again on its own after this long. */
-export const AUTO_SETUP_RETRY_MS = 24 * 60 * 60_000
-
-/** `no-prompt`: Linux with no administrator prompt to show (no desktop session): run `harness team setup` in a terminal. */
-export type AutoSetupState = 'unsupported' | 'signed-out' | 'dedicated' | 'running' | 'exists' | 'declined' | 'waiting' | 'not-shared'
- | 'no-prompt' | 'wanted' | 'started' | 'incomplete'
-
-/** A part of the Harness Team account besides the account itself that setup makes (#2765): its daemon (the service
- * file and the job loaded), and its privacy check passed (the team daemon's own report). */
-export type TeamPart = 'daemon' | 'privacy'
-const PART_WORDS: Record<TeamPart, string> = { daemon: 'the team daemon is not running', privacy: 'its privacy check has not passed' }
-/** What [missing] says, as one sentence part: "the team daemon is not running, and its privacy check has not passed". */
-export const missingDetail = (missing: readonly TeamPart[]): string => missing.map((part) => PART_WORDS[part]).join(', and ')
-
-/** What [TeamAutoSetup.status] answers. `detail`: a failed setup's own sentence, at most 300 characters. While it runs,
- * `step`: the step it is on (./command.ts `progress`), once one is said, and `elapsedMs`: how long it has run. */
-export interface TeamSetupStatus { state: 'none' | 'running' | 'exists' | 'declined' | 'failed' | 'incomplete'; detail?: string; step?: string
- elapsedMs?: number
- /** `incomplete`: the account is there, these parts are not (Set up repairs them). */
- missing?: TeamPart[] }
-
-/** The moment the person is at this Mac: they joined a Swarm, added this Mac to one, or opened the app (`startup`); or
- * they asked for it (`manual`: Desktop's explanation was accepted, or the machine row's Set up button). */
-export type AutoSetupReason = 'join' | 'contribute' | 'startup' | 'manual'
-export const AUTO_SETUP_REASONS: readonly AutoSetupReason[] = ['join', 'contribute', 'startup', 'manual']
-
-export interface AutoSetupDeps {
- platform: NodeJS.Platform
- session(): AuthSession | null
- readConfig(): TeamConfig | null
- accountExists(user: string): Promise<boolean>
- /** The parts besides the account that are not in place (#2765); none told, none counted (older callers, specs). */
- missing?(): Promise<readonly TeamPart[]>
- readDecision(): TeamSetupDecision | null
- writeDecision(decision: TeamSetupDecision): void
- /** `harness team setup --json`, as this account: its exit code and the JSON it answered (null when it said none).
- * [progress] hears each step as it goes. */
- setup(progress?: (step: string) => void, options?: { signInAgain?: boolean }): Promise<{ code: number; result: Record<string, unknown> | null }>
- now(): number
- log(line: string): void
- /** Linux: whether the administrator prompt can be shown from here (pkexec and a desktop session, ./admin.ts
- * `adminPromptShows`). Setup runs from the daemon with no terminal, so without one nothing could ask. */
- canPrompt?(): boolean
-}
-
-/** What a setup that made nothing answers: not cancelled, and not an account that exists but did not report in time.
- * Linux's own: no systemd or no tmux every account can run (the script stopped first), and no prompt to show. */
-const MADE_NOTHING = new Set(['SETUP_FAILED', 'NOT_INSTALLED', 'NOT_SIGNED_IN', 'RUN_AS_YOURSELF', 'INVALID_INPUT', 'BACKEND', 'EXPIRED', 'NOT_TEAM',
- 'NO_SYSTEMD', 'NO_TMUX', 'NO_PROMPT', 'NO_LOCAL_ACCOUNTS', 'NO_OWNER_SID'])
-
-export class TeamAutoSetup {
- private running: Promise<void> | null = null
- /** The running setup's start and step, for [status]. */
- private startedAt = 0
- private step: string | null = null
- constructor(private readonly deps: AutoSetupDeps) {}
-
- /**
- * Starts the setup when it is wanted, and answers at once with why it did or did not; the prompt is macOS's. At `startup`
- * it is wanted only while [sharedSwarm] says this Mac is in a Swarm with other people in it (false when it cannot say).
- * With [check] it starts nothing and answers `wanted` instead, for Desktop to explain the account first.
- * With [signInAgain] the person's own Set up signs an existing account in again for the account signed in here: the Swarm
- * found it serving another account of this computer (#3122), which no part of it shows.
- */
- async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false, check = false,
- { signInAgain = false, restart = false }: { signInAgain?: boolean; restart?: boolean } = {}): Promise<{ state: AutoSetupState }> {
- const state = await this.decide(reason, sharedSwarm, check, signInAgain, restart)
- // Every answer is said, not only a setup that starts: Macs in a Swarm went without the prompt and nothing on them said
- // why (2026-10-27). A check that finds it wanted starts nothing: that is Desktop's question, not an answer.
- if (state !== 'started' && state !== 'wanted') this.deps.log(`the Harness Team account was not offered (${reason}): ${state}`)
- return { state }
- }
-
- private async decide(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean>, check: boolean, signInAgain: boolean, restart: boolean): Promise<AutoSetupState> {
- const { deps } = this
- // A Mac, a Linux and a Windows computer (docs/superpowers/plans/2026-10-28-harness-team-account-windows.md).
- if (!teamLayout(deps.platform)) return 'unsupported'
- const session = deps.session()
- if (!session) return 'signed-out'
- if (session.kind === 'team') return 'dedicated'
- if (this.running) return 'running'
- if (deps.readConfig() || await deps.accountExists(TEAM_USER)) {
- // Done only when every part is there (#2765: an account with no daemon answered "already set up", and nothing
- // repaired it). A part missing is repaired only when the person asks (Set up): no password is asked for on its own.
- const again = reason === 'manual' && (signInAgain || restart)
- if (!(await this.missing()).length && !again) return 'exists'
- if (reason !== 'manual') return 'incomplete'
- } else if (reason !== 'manual') {
- const decision = deps.readDecision()
- if (decision?.state === 'declined') return 'declined'
- if (decision?.state === 'failed' && deps.now() - decision.at < AUTO_SETUP_RETRY_MS && deps.now() >= decision.at) return 'waiting'
- if (reason === 'startup' && !await sharedSwarm().catch(() => false)) return 'not-shared'
- }
- // Said before anything starts: a setup started anyway answered `started`, and Desktop told the person their system was
- // asking for a password when nothing could (the owner's daemon under systemd --user has no display). Nothing is
- // remembered: the terminal, or a session with a display, can still set it up.
- if (deps.platform === 'linux' && deps.canPrompt && !deps.canPrompt()) return 'no-prompt'
- if (check) return 'wanted'
- if (this.running) return 'running'
- this.running = this.run(reason === 'manual' && signInAgain).finally(() => { this.running = null })
- return 'started'
- }
-
- /**
- * Why this Mac has no Harness Team account, for its own Desktop's machine row: the person cancelled (the prompt, "Not
- * now" or `harness team remove`), setup failed and why, it is running now, or nothing was tried yet. Asks nothing.
- */
- async status(): Promise<TeamSetupStatus> {
- const { deps } = this
- if (this.running) {
- return { state: 'running', ...(this.step ? { step: this.step } : {}), elapsedMs: Math.max(0, deps.now() - this.startedAt) }
- }
- if (deps.readConfig() || await deps.accountExists(TEAM_USER)) {
- const missing = await this.missing()
- return missing.length ? { state: 'incomplete', missing: [...missing], detail: missingDetail(missing) } : { state: 'exists' }
- }
- const decision = deps.readDecision()
- if (!decision) return { state: 'none' }
- return { state: decision.state, ...(decision.state === 'failed' && decision.detail ? { detail: decision.detail } : {}) }
- }
-
- /** The parts not in place. One it cannot read counts as missing, the daemon, so Set up can still repair it. */
- private async missing(): Promise<readonly TeamPart[]> {
- if (!this.deps.missing) return []
- try { return await this.deps.missing() } catch { return ['daemon'] }
- }
-
- /** "Not now" in Desktop's explanation: not offered again on its own, as a cancelled prompt is not. */
- decline(): void {
- this.deps.writeDecision({ state: 'declined', at: this.deps.now() })
- }
-
- /** Waits for a setup this started, for a spec. */
- settled(): Promise<void> { return this.running ?? Promise.resolve() }
-
- private async run(signInAgain: boolean): Promise<void> {
- const { deps } = this
- deps.log(deps.platform === 'win32' ? 'setting up the Harness Team account: Windows asks for permission (User Account Control)'
- : `setting up the Harness Team account: ${deps.platform === 'darwin' ? 'macOS' : 'the system'} asks for an administrator password`)
- this.startedAt = deps.now()
- this.step = null
- let outcome: { code: number; result: Record<string, unknown> | null }
- try {
- outcome = await deps.setup((step) => { this.step = step }, ...signInAgain ? [{ signInAgain: true }] : [])
- } catch (error) {
- outcome = { code: 1, result: { ok: false, code: 'SETUP_FAILED', message: error instanceof Error ? error.message : String(error) } }
- }
- const code = typeof outcome.result?.code === 'string' ? outcome.result.code : null
- const message = typeof outcome.result?.message === 'string' ? outcome.result.message : undefined
- try {
- if (code === 'CANCELLED') {
- deps.writeDecision({ state: 'declined', at: deps.now() })
- deps.log('the Harness Team account prompt was cancelled: it is not offered again on its own (harness team setup offers it)')
- } else if (outcome.code !== 0 && code !== null && MADE_NOTHING.has(code)) {
- deps.writeDecision({ state: 'failed', at: deps.now(), ...(message ? { detail: message } : {}) })
- deps.log(`the Harness Team account was not set up: ${message ?? code}`)
- } else if (!deps.readConfig() && !await deps.accountExists(TEAM_USER).catch(() => false)) {
- // Whatever it answered, there is no account: remembered with why, so Desktop's lock ends with a reason instead of
- // waiting on a `none` (Scholes, 2026-11-04: osascript's 15 minutes, a code this CLI does not know, no answer).
- const detail = message ?? `Setup ended (exit ${outcome.code}) without making the Harness Team account.`
- deps.writeDecision({ state: 'failed', at: deps.now(), detail })
- deps.log(`the Harness Team account was not set up: ${detail}`)
- } else {
- deps.log(outcome.code === 0 ? 'the Harness Team account is set up' : `the Harness Team account was set up, with something to look at: harness team status`)
- for (const line of missingEngines(outcome.result)) deps.log(line)
- }
- } catch (error) {
- deps.log(`could not remember the Harness Team account setup: ${error instanceof Error ? error.message : String(error)}`)
- }
- }
-}
-
-/** What setup's JSON says of the engines it installed: one line for each that is not there, and how to add it. */
-function missingEngines(result: Record<string, unknown> | null): string[] {
- const engines = result?.engines
- if (!engines || typeof engines !== 'object') return []
- const names: Record<string, string> = { claude: 'Claude Code', codex: 'Codex' }
- return Object.entries(names).flatMap(([key, name]) => {
- const engine = (engines as Record<string, unknown>)[key]
- return engine && typeof engine === 'object' && (engine as { installed?: unknown }).installed === false
- ? [`${name} is not installed in the Harness Team account: harness team setup installs it`] : []
- })
-}
-
-/**
- * What is not in place of an existing Harness Team account (#2765), as `harness team status` reads it (./command.ts): the
- * daemon, when no job of its label runs; privacy, when the team daemon's own report does not say its check passed.
- */
-export async function teamMissingParts(deps: Pick<TeamCommandDeps, 'readConfig' | 'jobState' | 'readStatus'>, platform: NodeJS.Platform):
- Promise<TeamPart[]> {
- const layout = teamLayout(platform)
- if (!layout) return []
- const config = deps.readConfig()
- const job = await deps.jobState(config?.label ?? layout.service.label)
- const report = deps.readStatus(config?.statusFile ?? layout.statusFile)
- return [...job.pid === null ? ['daemon' as const] : [], ...report?.privacy?.passed === true ? [] : ['privacy' as const]]
-}
-
-/** The owner's daemon's own: this account's sign-in and data folder, and `harness team setup --json` run in this process. */
-export async function realTeamAutoSetup(dataDir: string, log: (line: string) => void): Promise<TeamAutoSetup> {
- const [{ readAuthSession }, { readTeamConfig }, { runGuestCommand }, { teamAccountExists }, { adminPromptShows }] = await Promise.all([
- import('../lib/authSession.js'), import('./config.js'), import('../lib/guestAccounts.js'), import('./deps.js'), import('./admin.js')])
- const file = teamSetupDecisionFile(dataDir)
- return new TeamAutoSetup({
- platform: process.platform,
- session: readAuthSession,
- readConfig: () => readTeamConfig(),
- // The platform's own account database: getent on Linux, id on a Mac.
- accountExists: teamAccountExists(runGuestCommand),
- // Read only: the job's state and the team daemon's report, as `harness team status` reads them, never as root.
- missing: async () => {
- const { teamCommandDeps } = await import('./deps.js')
- const refuse = async (): Promise<never> => { throw new Error('reading the parts changes nothing') }
- return teamMissingParts(teamCommandDeps({ stopDaemon: refuse, startDaemon: refuse }), process.platform)
- },
- readDecision: () => readTeamSetupDecision(file),
- writeDecision: (decision) => writeTeamSetupDecision(file, decision),
- setup: async (progress, options) => {
- const [{ teamCommand }, { teamCommandDeps }] = await Promise.all([import('./command.js'), import('./deps.js')])
- const lines: string[] = []
- const refuse = async (): Promise<never> => { throw new Error('setup does not restart the daemon') }
- const code = await teamCommand(['setup', '--json', ...options?.signInAgain ? ['--sign-in-again'] : []], { ...teamCommandDeps({ stopDaemon: refuse, startDaemon: refuse }),
- out: (line) => lines.push(line), err: (line) => lines.push(line), interactive: false, ...(progress ? { progress } : {}) })
- const last = [...lines].reverse().find((line) => line.startsWith('{'))
- let result: Record<string, unknown> | null = null
- try { result = last ? JSON.parse(last) as Record<string, unknown> : null } catch { /* said nothing readable */ }
- return { code, result }
- },
- now: () => Date.now(),
- log,
- // Read at each offer: this daemon's environment, as `harness team setup --json` above would run in it.
- canPrompt: () => adminPromptShows(),
- })
-}
diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.ts
index 199a7a039..ac3c392b9 100644
--- a/cli/src/team/command.spec.ts
+++ b/cli/src/team/command.spec.ts
@@ -4,13 +4,12 @@
import { describe, expect, it, vi } from 'vitest'
import { signInOf, type AuthSession } from '../lib/authSession.js'
import { SIGN_OUT_BUTTON_FLAG, signOutAsked } from '../lib/signOut.js'
-import { NO_PROMPT_MESSAGE, type AdminScript, type RunAdmin } from './admin.js'
-import { REPAIR_PROMPT, SETUP_PROMPT, teamCommand, type TeamCommandDeps } from './command.js'
+import type { AdminScript, RunAdmin } from './admin.js'
+import { teamCommand, type TeamCommandDeps } from './command.js'
import type { TeamConfig } from './config.js'
import type { PrivacyResult, TeamStatus } from './privacy.js'
import type { TeamEngines } from './engines.js'
import { parseLaunchctlPrint, parseSystemctlShow } from './deps.js'
-import { LINUX_NO_SYSTEMD, LINUX_NO_TMUX } from './script.js'
const OWNER_HOME = '/Users/owner-placeholder'
const CODE = `hnh_${'b'.repeat(43)}`
@@ -91,165 +90,27 @@ describe('harness team', () => {
it('prints its help, and refuses an unknown verb', async () => {
const f = fake()
expect(await teamCommand([], f.deps)).toBe(0)
- expect(f.out[0]).toContain('Usage: harness team <setup | status | model | logs | sign-in | remove | on | off>')
+ expect(f.out[0]).toContain('Usage: harness team <status | logs | remove | on | off>')
+ // Swarm v3 has no Team accounts (#4221): nothing signs a Team account's engines in or gives it a model.
+ expect(f.out[0]).not.toMatch(/sign-in|model/)
expect(await teamCommand(['frobnicate'], f.deps)).toBe(2)
})
})
describe('harness team setup', () => {
- it('copies the engines this Mac already has into the team account, instead of downloading them (#3169)', async () => {
- const codex = { packageName: '@openai/codex', dir: `${OWNER_HOME}/.local/lib/node_modules/@openai/codex`, bin: 'codex', binPath: 'bin/codex.js' }
+ it('refuses before any prompt, in words and in JSON: Swarm v3 has no Team accounts (#4221)', async () => {
const f = fake({ statusAfter: reported })
- const installed = f.deps.installed()
- f.deps.installed = () => ({ ...installed, engineCopies: [codex] })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- const { script } = f.built[0]!
- expect(script).toContain(`copy_engine '@openai/codex' '${OWNER_HOME}/.local/lib/node_modules/@openai/codex' 'codex' 'bin/codex.js'`)
- expect(script).toContain("[ -n \"$copied_claude\" ] || set -- \"$@\" '@anthropic-ai/claude-code'")
- })
-
- it('says what it will make, runs one privileged script, and waits for the team daemon to sign in and pass its check', async () => {
- const f = fake({ statusAfter: reported, env: { BACKEND_WS_URL: 'wss://backend.example.test', HARNESS_AUTH_DIR: '/tmp/auth' } })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- expect(f.admin).toHaveBeenCalledTimes(1)
- expect(f.prompts[0]).toContain('Harness Team')
- const { script, files } = f.built[0]!
- expect(script).toContain("OWNER='owner-placeholder'")
- expect(script).toContain("STAGE='/private/var/folders/aa/T/harness-team-stage'")
- expect(script).toContain("'HARNESS_AUTH_DIR=/tmp/auth'")
- const written = JSON.parse(files!['team.json']!) as TeamConfig
- expect(written).toMatchObject({ user: 'harnessteam', ownerHome: OWNER_HOME, port: 18493, node: '/Users/harnessteam/.harness/runtime/node-v1/bin/node',
- env: { BACKEND_WS_URL: 'wss://backend.example.test' } })
- expect(files!['team.plist']).toContain('<string>wss://backend.example.test</string>')
- expect(files!['team.plist']).not.toContain('HARNESS_AUTH_DIR')
- const text = f.out.join('\n')
- expect(text).toContain('Harness Team (harnessteam)')
- expect(text).toContain('/Library/LaunchDaemons/ai.autonomous.harness.team.plist')
- expect(text).toContain('✓ The Harness Team account is signed in.')
- expect(text).toContain('✓ Private')
- // The engines setup installed in the team account, and how to sign them in (none were reported in this run).
- expect(text).toContain('engines ? not reported yet')
+ expect(await teamCommand(['setup'], f.deps)).toBe(1)
+ expect(f.err.join('\n')).toContain('Swarm v3 has no Team accounts')
+ const json = fake({ statusAfter: reported })
+ expect(await teamCommand(['setup', '--json'], json.deps)).toBe(1)
+ expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: false, code: 'TEAM_ACCOUNTS_REMOVED' })
+ expect(f.admin).not.toHaveBeenCalled()
+ expect(json.admin).not.toHaveBeenCalled()
})
// Scholes, 2026-11-04: a new member waited about 7 minutes after the password with no sign of progress. Setup says
// which step it is on: the password first, then each step the script reports, then the team daemon's report.
- it('says each step as it goes: the password, the script\'s own steps, then the team daemon\'s report', async () => {
- const steps: string[] = []
- const f = fake({ statusAfter: reported, progress: (step) => steps.push(step) })
- f.admin.mockImplementationOnce(async (build, _prompt, _via, progress) => {
- build('/private/var/folders/aa/T/harness-team-stage')
- expect(steps).toEqual(['password'])
- progress?.('account'); progress?.('engines')
- return { ok: true, stdout: 'harness: handed a sign-in to the team account\n' }
- })
- expect(await teamCommand(['setup', '--json'], f.deps)).toBe(0)
- expect(steps).toEqual(['password', 'account', 'engines', 'report'])
- })
-
- it('asks to create the account on a Mac without one, and to repair it on a Mac that has it', async () => {
- const first = fake({ statusAfter: reported })
- await teamCommand(['setup'], first.deps)
- expect(first.prompts[0]).toBe(SETUP_PROMPT)
- expect(first.out[0]).toContain('Harness will set up a separate account')
- for (const over of [{ readConfig: () => config }, { accountExists: vi.fn(async () => true) }]) {
- const again = fake({ statusAfter: reported, ...over })
- await teamCommand(['setup'], again.deps)
- expect(again.prompts[0]).toBe(REPAIR_PROMPT)
- expect(again.prompts[0]).toContain('repair the Harness Team account')
- expect(again.out[0]).toContain('Harness will repair the Harness Team account')
- }
- // What setup says it made is what it makes now: a password nobody knows, and listed.
- expect(first.out.join('\n')).toContain('a standard user with a random password nobody knows, listed in Users & Groups')
- })
-
- it('shows the team account\'s engines as its daemon reported them in this run, and how to sign them in', async () => {
- const f = fake({ statusAfter: (t) => ({ ...reported(t), engines: { checkedAt: t + 3_000, claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: false } } }) })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- const text = f.out.join('\n')
- expect(text).toContain('Claude Code ✓ installed · ✗ not signed in')
- expect(text).toContain(' codex login --device-auth Codex')
- const json = fake({ statusAfter: (t) => ({ ...reported(t), engines: { checkedAt: t - 1, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true } } }) })
- await teamCommand(['setup', '--json'], json.deps)
- expect(JSON.parse(json.out.at(-1)!)).toMatchObject({ ok: true, engines: null })
- })
-
- it('forgets a prompt Desktop saw cancelled once it makes the account, and a removal is remembered as declined', async () => {
- const decision = { clear: vi.fn(), decline: vi.fn() }
- const made = fake({ statusAfter: reported, setupDecision: decision })
- expect(await teamCommand(['setup'], made.deps)).toBe(0)
- expect(decision.clear).toHaveBeenCalledTimes(1)
- const cancelled = fake({ adminResult: { ok: false, code: 'CANCELLED', message: 'x' }, setupDecision: decision })
- await teamCommand(['setup'], cancelled.deps)
- expect(decision.clear).toHaveBeenCalledTimes(1)
- const removed = fake({ readConfig: () => config, setupDecision: decision })
- expect(await teamCommand(['remove'], removed.deps)).toBe(0)
- expect(decision.decline).toHaveBeenCalledTimes(1)
- expect(removed.out.join('\n')).toContain('will not make it again on its own')
- const failing = fake({ statusAfter: reported, setupDecision: { clear: () => { throw new Error('read-only') }, decline: vi.fn() } })
- expect(await teamCommand(['setup'], failing.deps)).toBe(0)
- })
-
- it('reports a failed privacy check or sign-in, and returns failure', async () => {
- const f = fake({ statusAfter: (t) => ({ version: 1, signIn: { state: 'failed', at: t + 1, detail: 'code refused' },
- privacy: { passed: false, item: 'gitconfig', detail: 'The team account could read ~/.gitconfig.', checkedAt: t + 1 } }) })
- expect(await teamCommand(['setup'], f.deps)).toBe(1)
- expect(f.err.join('\n')).toContain('did not sign in: code refused')
- expect(f.err.join('\n')).toContain('Not private (gitconfig)')
- })
-
- it('says when the daemon has not reported in time, ignoring an older report', async () => {
- const f = fake({ statusAfter: (t) => ({ version: 1, privacy: { passed: true, checkedAt: t - 10 } }) })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- expect(f.out.join('\n')).toContain('has not reported its privacy check yet')
- expect(f.out.join('\n')).toContain('has not signed in yet')
- })
-
- it('does not wait for a sign-in the script did not hand over, and asks again with --sign-in-again', async () => {
- const f = fake({ adminResult: { ok: true, stdout: '' }, statusAfter: (t) => ({ version: 1, privacy: { passed: true, checkedAt: t + 1 } }) })
- expect(await teamCommand(['setup', '--json'], f.deps)).toBe(0)
- expect(JSON.parse(f.out.at(-1)!)).toMatchObject({ ok: true, user: 'harnessteam', label: 'ai.autonomous.harness.team', privacy: { passed: true } })
- expect(f.built[0]!.script).toContain("SIGN_IN='missing'")
- const again = fake({ statusAfter: reported })
- await teamCommand(['setup', '--sign-in-again'], again.deps)
- expect(again.built[0]!.script).toContain("SIGN_IN='always'")
- })
-
- it('changes nothing when the prompt is cancelled, and says how to finish a script that stopped', async () => {
- const cancelled = fake({ adminResult: { ok: false, code: 'CANCELLED', message: 'x' } })
- expect(await teamCommand(['setup'], cancelled.deps)).toBe(1)
- expect(cancelled.err[0]).toContain('Nothing was changed')
- const stopped = fake({ adminResult: { ok: false, code: 'FAILED', message: 'launchd would not start the team daemon' } })
- expect(await teamCommand(['setup', '--json'], stopped.deps)).toBe(1)
- expect(JSON.parse(stopped.out.at(-1)!)).toMatchObject({ ok: false, code: 'SETUP_FAILED' })
- // The script's reason has no full stop of its own; the sentence after it must not run on.
- const unsigned = fake({ adminResult: { ok: false, code: 'FAILED', message: 'could not get a sign-in code from your Harness sign-in; the team daemon runs without a new sign-in' } })
- expect(await teamCommand(['setup'], unsigned.deps)).toBe(1)
- expect(unsigned.err[0]).toBe('✗ The Harness Team account was not finished: could not get a sign-in code from your Harness sign-in; '
- + 'the team daemon runs without a new sign-in. Run `harness team setup` again; it repairs what is there.')
- const failedRemove = fake({ readConfig: () => config, adminResult: { ok: false, code: 'FAILED', message: 'The script stopped (exit 2).' } })
- expect(await teamCommand(['remove'], failedRemove.deps)).toBe(1)
- expect(failedRemove.err[0]).toBe('✗ The Harness Team account was not fully removed: The script stopped (exit 2). Run `harness team remove` again.')
- })
-
- it('refuses where it cannot help, before any prompt', async () => {
- const cases: Array<[Partial<TeamCommandDeps>, string]> = [
- // Windows has the account too now (the 'on Windows' tests below): a system with none is refused.
- [{ platform: 'freebsd' }, 'harness team on'],
- [{ uid: () => 0 }, 'not with sudo'],
- [{ session: () => null }, 'Sign this computer in first'],
- [{ session: () => ({ ...computer, kind: 'team' }) }, 'already runs team work only'],
- [{ user: () => 'harnessteam' }, 'not the Harness Team account'],
- [{ exists: () => false }, 'not installed'],
- [{ env: { BACKEND_WS_URL: 'wss://x/$(id)' } }, 'BACKEND_WS_URL'],
- [{ home: () => "/Users/o'brien" }, 'plain absolute path'],
- ]
- for (const [over, says] of cases) {
- const f = fake(over)
- expect(await teamCommand(['setup'], f.deps), says).toBe(1)
- expect(f.err.join('\n'), says).toContain(says)
- expect(f.admin).not.toHaveBeenCalled()
- }
- })
})
describe('harness team status', () => {
@@ -288,16 +149,15 @@ describe('harness team status', () => {
expect(JSON.parse(json.out[0]!).purges).toEqual({ pending: 2, unreadable: false, at: 5 })
})
- it('says whether the team account\'s engines are installed and signed in, and exactly how to sign them in', async () => {
+ it('says first that its daemon stops once no agent runs in it and how to delete it, not how to sign its engines in (#4221)', async () => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
f.status.set(STATUS, { version: 1, engines: { checkedAt: 1_000_000 - 60_000, claude: { installed: true, signedIn: false }, codex: { installed: false, signedIn: null } } })
await teamCommand(['status'], f.deps)
const text = f.out.join('\n')
- expect(text).toContain('engines Claude Code ✓ installed · ✗ not signed in')
- expect(text).toContain('Codex ✗ not installed · harness team setup installs it')
- expect(text).toContain('(checked 60s ago)')
- expect(text).toContain('in Harness, open a terminal on this Mac\'s Harness Team machine')
- expect(text).toContain(' claude Claude Code')
+ const said = 'Swarm v3 has no Team accounts: its daemon stops once no agent runs in it. harness team remove deletes the account, its home and its daemon.'
+ expect(f.out.findIndex(line => line.includes(said))).toBeGreaterThan(-1)
+ expect(f.out.findIndex(line => line.includes(said))).toBeLessThan(f.out.findIndex(line => line.includes(' daemon ')))
+ expect(text).not.toMatch(/sign(ed)? (them )?in|harness team sign-in|engines {5}/)
const json = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
json.status.set(STATUS, { version: 1, engines: { checkedAt: 5, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true } } })
await teamCommand(['status', '--json'], json.deps)
@@ -353,7 +213,7 @@ describe('harness team status', () => {
expect(JSON.parse(f.out[0]!)).toMatchObject({ account: true, user: 'harnessteam', label: 'ai.autonomous.harness.team', job: { pid: 4242 }, ownerHomeMode: '700', privacy: null })
const none = fake()
await teamCommand(['status'], none.deps)
- expect(none.out[0]).toContain('No Harness Team account on this computer. harness team setup makes one.')
+ expect(none.out[0]).toContain('No Harness Team account on this computer.')
const linux = fake({ platform: 'linux', session: () => ({ ...computer, kind: 'team' }) })
await teamCommand(['status'], linux.deps)
expect(linux.out[0]).toContain('runs team work only')
@@ -834,54 +694,6 @@ describe('on Linux', () => {
...over,
})
- it('setup runs the Linux script through the administrator prompt and waits for the team daemon\'s status file', async () => {
- const seen: string[] = []
- const f = onLinux({ statusAfter: reported, readStatus: (path) => { seen.push(path); return reported(1_000_000) } })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- expect(f.vias[0]).toBe('prompt')
- expect(seen).toContain(LINUX_STATUS)
- const { script, files } = f.built[0]!
- expect(script).toContain('useradd -m -d "$TEAM_HOME"')
- expect(script).toContain("TEAM_HOME='/home/harnessteam'")
- expect(script).toContain(`OWNER_HOME='${LINUX_HOME}'`)
- expect(Object.keys(files!).sort()).toEqual(['team.json', 'team.service'])
- expect(files!['team.service']).toContain('\nUser=harnessteam\n')
- expect(JSON.parse(files!['team.json']!)).toMatchObject({ home: '/home/harnessteam', ownerHome: LINUX_HOME, label: 'harness-team.service',
- plist: '/etc/systemd/system/harness-team.service', statusFile: LINUX_STATUS, node: '/home/harnessteam/.harness/runtime/node-v1/bin/node' })
- const text = f.out.join('\n')
- expect(text).toContain('on this computer')
- expect(text).not.toMatch(/Mac|macOS|LaunchDaemon|Users & Groups/)
- expect(text).toContain('harness-team.service, a systemd unit at /etc/systemd/system/harness-team.service, running as harnessteam on port 18493')
- expect(text).toContain('✓ Private')
- })
-
- it('setup asks with sudo in a terminal, which works without a desktop session', async () => {
- const f = onLinux({ statusAfter: reported, interactive: true })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- expect(f.vias[0]).toBe('sudo')
- expect(f.prompts[0]).toBe('Harness wants to create a separate account, Harness Team, for Swarm work on this computer, so teammates\' agents cannot read your files.')
- expect(f.out[0]).toContain('sudo asks for your password here')
- })
-
- it('setup passes on why Linux refused: no systemd, no tmux, no prompt', async () => {
- const cases: Array<[Awaited<ReturnType<RunAdmin>>, string, string]> = [
- [{ ok: false, code: 'FAILED', status: 3, message: LINUX_NO_SYSTEMD }, 'NO_SYSTEMD', 'systemd'],
- [{ ok: false, code: 'FAILED', status: 3, message: LINUX_NO_TMUX }, 'NO_TMUX', 'apt install tmux'],
- [{ ok: false, code: 'NO_PROMPT', message: NO_PROMPT_MESSAGE }, 'NO_PROMPT', 'run harness team setup in a terminal'],
- ]
- for (const [adminResult, code, says] of cases) {
- const f = onLinux({ adminResult })
- expect(await teamCommand(['setup', '--json'], f.deps), code).toBe(1)
- const answer = JSON.parse(f.out.at(-1)!) as { code: string; message: string }
- expect(answer.code).toBe(code)
- expect(answer.message).toContain(says)
- }
- // Another stop with exit 3 is a failed setup, as on a Mac.
- const other = onLinux({ adminResult: { ok: false, code: 'FAILED', status: 3, message: 'setfacl is missing on this computer: the Harness Team account needs it' } })
- await teamCommand(['setup', '--json'], other.deps)
- expect(JSON.parse(other.out.at(-1)!)).toMatchObject({ code: 'SETUP_FAILED' })
- })
-
it('status reads systemd and prints what Linux setup made, and how to remove it by hand', async () => {
const f = onLinux({ readConfig: () => linuxConfig, accountExists: vi.fn(async () => true) })
f.status.set(LINUX_STATUS, { version: 1, signIn: { state: 'signed-in', at: 1_000_000 - 30_000 }, privacy: { passed: true, checkedAt: 1_000_000 - 60_000 } })
@@ -962,84 +774,7 @@ describe('on Windows', () => {
})
}
- it('setup runs the Windows script through User Account Control, then hands the sign-in over as the owner and starts the task', async () => {
- const handed: string[] = []
- const seen: string[] = []
- // Nothing reported before the hand-over: the account has no sign-in yet.
- const f = onWindows({ handedOver: handed, readStatus: (path) => { seen.push(path); return handed.length ? reported(1_000_000) : null } })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- expect(f.vias[0]).toBe('prompt')
- const { script, files } = f.built[0]!
- expect(script).toContain("$OWNER = 'DELL'")
- expect(script).toContain(`$OWNER_SID = '${WIN_SID}'`)
- expect(script).toContain(`$OWNER_HOME = '${WIN_HOME}'`)
- expect(script).toContain(`$PTY_SRC = '${WIN_HOME}\\.harness\\runtime\\pty\\0.2.4'`)
- // The elevated script never mints the code: UAC may run it as another administrator.
- expect(script).not.toContain('__handoff')
- expect(Object.keys(files!).sort()).toEqual(['team.json', 'team.xml'])
- expect(files!['team.xml']).toContain('<UserId>harnessteam</UserId>')
- expect(files!['team.xml']).toContain(`(A;;FRFX;;;${WIN_SID})`)
- // The task runs the version `cli\current` names, as the owner's launcher does; setup lays the owner's version down.
- expect(files!['team.xml']).toContain('set /p V=&lt;&quot;C:\\Users\\harnessteam\\.harness\\cli\\current&quot;')
- expect(script).toContain("$CliVersion = '0.4.97'")
- expect(JSON.parse(files!['team.json']!)).toMatchObject({ owner: 'DELL', ownerSid: WIN_SID, ownerHome: WIN_HOME, home: 'C:\\Users\\harnessteam',
- sentinel: `${WIN_HOME}\\.harness-team-privacy`, statusFile: WIN_STATUS, label: '\\Harness\\Harness Team',
- node: `C:\\Users\\harnessteam\\.harness\\runtime\\${NODE}\\node.exe`, cli: 'C:\\Users\\harnessteam\\.harness\\cli\\0.4.97\\cli.js' })
- // After the prompt, as the owner: a fresh code, written to the handover folder, then the task.
- expect(f.post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team', hostMachineId: 'm1' }, { authorization: 'Bearer x' })
- expect(handed).toEqual([CODE])
- expect(f.deps.startTeamTask).toHaveBeenCalledTimes(1)
- expect(f.admin.mock.invocationCallOrder[0]).toBeLessThan(f.post.mock.invocationCallOrder[0]!)
- expect(seen).toContain(WIN_STATUS)
- const text = f.out.join('\n')
- expect(text).toContain('Windows asks for permission once (User Account Control).')
- expect(text).toContain('\\Harness\\Harness Team, a scheduled task at startup, running as harnessteam on port 18493')
- expect(text).not.toMatch(/Mac|macOS|LaunchDaemon|systemd|sudo|mode 700/)
- expect(text).toContain('✓ The Harness Team account is signed in.')
- expect(text).toContain('✓ Private')
- })
-
// Task #2686: on Windows the sign-in and the daemon's start come after the elevated script, from the owner.
- it('setup says the sign-in and the daemon steps around the handover, then waits for the report', async () => {
- const handed: string[] = []
- const steps: string[] = []
- const f = onWindows({ handedOver: handed, progress: (step) => steps.push(step), readStatus: () => handed.length ? reported(1_000_000) : null })
- f.admin.mockImplementationOnce(async (build, _prompt, _via, progress) => {
- build(`${WIN_HOME}\\AppData\\Local\\Temp\\harness-team-stage`)
- progress?.('account'); progress?.('engines')
- return { ok: true, stdout: '' }
- })
- expect(await teamCommand(['setup', '--json'], f.deps)).toBe(0)
- expect(steps).toEqual(['password', 'account', 'engines', 'sign-in', 'daemon', 'report'])
- })
-
- it('setup starts the task again up to five times, and keeps a sign-in already there unless asked again', async () => {
- let tries = 0
- const f = onWindows({ statusAfter: reported, startTeamTask: vi.fn(async () => ++tries >= 3) })
- expect(await teamCommand(['setup'], f.deps)).toBe(0)
- expect(f.deps.startTeamTask).toHaveBeenCalledTimes(3)
- const handed: string[] = []
- const signedIn = onWindows({ handedOver: handed, readConfig: () => winConfig,
- readStatus: () => ({ version: 1, signIn: { state: 'signed-in', at: 1 }, privacy: { passed: true, checkedAt: 2_000_000 } }) })
- expect(await teamCommand(['setup'], signedIn.deps)).toBe(0)
- expect(handed).toEqual([])
- expect(await teamCommand(['setup', '--sign-in-again'], signedIn.deps)).toBe(0)
- expect(handed).toEqual([CODE])
- })
-
- it('setup says why when the task will not start, or Windows makes no local account', async () => {
- const f = onWindows({ startTeamTask: vi.fn(async () => false) })
- expect(await teamCommand(['setup', '--json'], f.deps)).toBe(1)
- expect(f.deps.startTeamTask).toHaveBeenCalledTimes(5)
- expect(JSON.parse(f.out.at(-1)!)).toMatchObject({ code: 'SETUP_FAILED' })
- const local = onWindows({ adminResult: { ok: false, code: 'FAILED', status: 5, message: 'Windows would not make a local account here (policy); nothing was changed' } })
- expect(await teamCommand(['setup', '--json'], local.deps)).toBe(1)
- expect(JSON.parse(local.out.at(-1)!)).toMatchObject({ code: 'NO_LOCAL_ACCOUNTS' })
- const noSid = onWindows({ ownerSid: vi.fn(async () => null) })
- expect(await teamCommand(['setup', '--json'], noSid.deps)).toBe(1)
- expect(noSid.admin).not.toHaveBeenCalled()
- })
-
it('status reads Task Scheduler and prints what Windows setup made, and how to remove it by hand', async () => {
const f = onWindows({ readConfig: () => winConfig, accountExists: vi.fn(async () => true),
jobState: vi.fn(async () => ({ loaded: true, pid: 4242, state: 'Running' })) })
@@ -1126,16 +861,14 @@ describe('harness team logs and sign-in', () => {
expect(f.out.join('\n')).toContain('create pane open')
})
- it('refuses the sign-in where it cannot run, naming what to do instead', async () => {
- const windows = fake({ platform: 'win32', readConfig: () => config as never })
- expect(await teamCommand(['sign-in', 'claude'], windows.deps)).toBe(1)
- expect(windows.err.join('\n')).toContain('On Windows, sign in from Harness')
- const noTerminal = fake({ readConfig: () => config as never, interactive: false })
- expect(await teamCommand(['sign-in', 'codex'], noTerminal.deps)).toBe(1)
- expect(noTerminal.err.join('\n')).toContain('Run it in a terminal')
- const wrong = fake({ readConfig: () => config as never, interactive: true })
- expect(await teamCommand(['sign-in', 'vim'], wrong.deps)).toBe(1)
- expect(wrong.err.join('\n')).toContain('Name claude or codex')
+ it('signs no engine in and sets no model: Swarm v3 has no Team accounts (#4221)', async () => {
+ for (const argv of [['sign-in', 'claude'], ['model', 'set', 'openai', '--model', 'gpt-x']]) {
+ const f = fake({ readConfig: () => config as never, interactive: true })
+ expect(await teamCommand(argv, f.deps), argv[0]).toBe(1)
+ expect(f.err.join('\n'), argv[0]).toContain('Swarm v3 has no Team accounts')
+ expect(f.admin, argv[0]).not.toHaveBeenCalled()
+ }
})
+
})
diff --git a/cli/src/team/command.ts b/cli/src/team/command.ts
index 0fb377952..ef6a17f0e 100644
--- a/cli/src/team/command.ts
+++ b/cli/src/team/command.ts
@@ -1,5 +1,5 @@
/**
- * `harness team setup | status | remove | on | off` (docs/plans/2026-10-24-swarm-team-account.md, Task 2).
+ * `harness team status | remove | on | off` (docs/plans/2026-10-24-swarm-team-account.md, Task 2).
*
* On a Mac or a Linux computer, Swarm work from teammates runs in the Harness Team account: a separate standard user with
* its own Harness daemon, which cannot read the owner's files (Linux: docs/superpowers/plans/2026-10-28-harness-team-account-linux.md).
@@ -13,54 +13,37 @@
* Nothing here falls back to the owner: a team account that is missing, signed out or not private is reported, and
* team work does not run as the owner instead.
*/
-import { spawnSync } from 'node:child_process'
import type { AgentTmpState } from '../lib/agentTmp.js'
import { sameSignIn, type AuthSession } from '../lib/authSession.js'
import { SIGN_OUT_BUTTON_FLAG, type SignOutAsked } from '../lib/signOut.js'
-import { psQuote, type AdminVia, type RunAdmin } from './admin.js'
-import { teamConfigJson, type TeamConfig } from './config.js'
-import { engineLines, type TeamEngines } from './engines.js'
-import { teamModelSet } from './model.js'
-import type { TeamModelHandoff } from './modelHandoff.js'
+import { psQuote, type RunAdmin } from './admin.js'
+import type { TeamConfig } from './config.js'
+import type { TeamEngines } from './engines.js'
import { handedTeamSignInEpoch, mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Delete, type Get, type Post } from './handoff.js'
import {
SENTINEL_NAME, TEAM_PORT, TEAM_REAL_NAME, TEAM_STATUS_FILE,
- TEAM_USER, TeamInputError, carriedBackendEnv, checkSid, pathCheck, teamLayout, teamPaths, userCheck, type TeamLayout, type TeamPlatform,
+ TEAM_USER, TeamInputError, pathCheck, teamLayout, teamPaths, userCheck, type TeamLayout, type TeamPlatform,
} from './layout.js'
import type { PrivacyResult, TeamStatus } from './privacy.js'
-import {
- LINUX_NO_SYSTEMD, LINUX_NO_TMUX, REMOVE_REFUSED, buildLinuxRemoveScript, buildLinuxSetupScript, buildRemoveScript,
- buildSetupScript, teamLaunchdPlist, teamSystemdUnit, type EngineCopy, type RemoveScriptInput, type SetupScriptInput, type TeamPlistInput,
-} from './script.js'
+import { REMOVE_REFUSED, buildLinuxRemoveScript, buildRemoveScript, type EngineCopy, type RemoveScriptInput } from './script.js'
import { windowsTeamPaths } from './windowsLayout.js'
-import { WINDOWS_STAGED, buildWindowsRemoveScript, buildWindowsSetupScript, teamTaskXml } from './windowsScript.js'
+import { buildWindowsRemoveScript } from './windowsScript.js'
/** How a platform with a Harness Team account makes and removes it (Windows:
* docs/superpowers/plans/2026-10-28-harness-team-account-windows.md). */
interface TeamScripts {
- setup(input: TeamSetupInput): string
remove(input: RemoveScriptInput): string
- /** The team daemon's service definition (Windows: its task, which its owner may start). */
- service(input: TeamPlistInput & { ownerSid?: string }): string
- /** Its name in the staging folder, where the setup script installs it from. */
- serviceFile: string
}
-/** What the Windows script takes beyond the others' input (./windowsScript.ts). */
-type TeamSetupInput = SetupScriptInput & { ownerSid?: string; ptyDir?: string | null }
-
const SCRIPTS: Record<TeamPlatform, TeamScripts> = {
- darwin: { setup: buildSetupScript, remove: buildRemoveScript, service: teamLaunchdPlist, serviceFile: 'team.plist' },
- linux: { setup: buildLinuxSetupScript, remove: buildLinuxRemoveScript, service: teamSystemdUnit, serviceFile: 'team.service' },
- win32: {
- setup: (input) => buildWindowsSetupScript({ ...input, ownerSid: input.ownerSid ?? '' }),
- remove: buildWindowsRemoveScript, service: teamTaskXml, serviceFile: WINDOWS_STAGED.task,
- },
+ darwin: { remove: buildRemoveScript },
+ linux: { remove: buildLinuxRemoveScript },
+ win32: { remove: buildWindowsRemoveScript },
}
interface TeamHere { layout: TeamLayout; scripts: TeamScripts; mac: boolean; windows: boolean; where: string; system: string }
-/** This computer's layout and scripts, or null where `harness team setup` makes no account. */
+/** This computer's layout and scripts, or null where no Harness Team account was ever made. */
function teamHere(platform: NodeJS.Platform): TeamHere | null {
const layout = teamLayout(platform)
if (!layout) return null
@@ -71,17 +54,12 @@ function teamHere(platform: NodeJS.Platform): TeamHere | null {
}
export const TEAM_USAGE = [
- 'Usage: harness team <setup | status | model | logs | sign-in | remove | on | off> [--json]',
+ 'Usage: harness team <status | logs | remove | on | off> [--json]',
'',
- ' setup make the Harness Team account on this Mac, Linux or Windows computer for Swarm work: a separate standard user,',
- ` "Harness Team" (${TEAM_USER}), whose own Harness daemon runs teammates' agents so they cannot read your files.`,
- ' The system asks for an administrator password once. It installs the account\'s own Claude Code and Codex,',
- ' which you sign in once in a terminal on its machine. Running it again repairs it (--sign-in-again: a new sign-in)',
- ' status whether the account exists and runs, its sign-in, privacy check and engines, and everything setup made',
- ' model the team account\'s own model API instead of your subscription: `harness team model set <provider> --model <id>`',
- ' (asks for the key, hidden; --clear undoes it)',
+ ' A Harness Team account was a separate user made for Swarm work before Swarm v3, which has none: `setup` makes no new',
+ ' one. Its daemon stops once no agent runs in it.',
+ ' status whether the account and its daemon are still there, its privacy check, and everything setup made',
' logs the team daemon\'s last 40 lines (--lines N): what its agents are doing',
- ' sign-in sign its Claude Code or Codex in, here in this terminal: harness team sign-in claude',
' remove delete the account, its home folder and its daemon; your home stays private. Run it in Terminal: sudo',
' asks for your password, and macOS asks once to let Terminal administer your computer, which it needs',
' on for a computer used only for agents (a Mac mini, a Linux or Windows box): sign it in for team work',
@@ -91,18 +69,10 @@ export const TEAM_USAGE = [
/** What the administrator prompt says (sudo's prompt on Linux; pkexec shows polkit's own words). */
const prompts = (where: string) => ({
- setup: `Harness wants to create a separate account, Harness Team, for Swarm work on ${where}, so teammates' agents cannot read your files.`,
- repair: `Harness wants to repair the Harness Team account, which runs Swarm work on ${where} so teammates' agents cannot read your files.`,
remove: `Harness wants to remove the Harness Team account, its home folder and its daemon from ${where}.`,
})
-export const SETUP_PROMPT = prompts('this Mac').setup
-/** The same script on a Mac that has the account: it repairs what is there. (The dialog's title, "osascript", is the
- * process that asks, and osascript cannot change it.) */
-export const REPAIR_PROMPT = prompts('this Mac').repair
export const REMOVE_PROMPT = prompts('this Mac').remove
-/** How long setup waits for the team daemon to sign in and report its privacy check. */
-export const SETUP_REPORT_WAIT_MS = 90_000
export interface Installed {
/** The owner's installed CLI folder and its cli.js. */
@@ -185,9 +155,6 @@ export interface TeamCommandDeps {
stopDaemon(): Promise<boolean>
startDaemon(): Promise<void>
signIn?(restart: boolean): Promise<void>
- /** What Desktop's automatic offer remembers (./autoSetup.ts): a setup that made the account forgets a cancelled prompt,
- * and a removal is remembered as one, so the account is not made again on its own. */
- setupDecision?: { clear(): void; decline(): void }
/** Windows, as the owner and before User Account Control: this account's SID (`whoami /user`), or null. */
ownerSid?(): Promise<string | null>
@@ -195,8 +162,6 @@ export interface TeamCommandDeps {
handOver?(code: string): void
/** Windows: asks Task Scheduler to start the team daemon's task; false when it would not. */
startTeamTask?(): Promise<boolean>
- /** Windows: leaves a model API for the Team daemon (./modelHandoff.ts); a spec names its own. */
- handModel?(handoff: TeamModelHandoff): void
}
export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promise<number> {
@@ -210,11 +175,9 @@ export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promis
}
try {
switch (verb) {
- case 'setup': return await setup(deps, json, flags.includes('--sign-in-again'))
+ case 'setup': case 'model': case 'sign-in': return removed(deps, json)
case 'status': return await status(deps, json)
- case 'model': return await teamModelSet(deps, words, flags, json)
case 'logs': return await teamLogs(deps, words, flags, json)
- case 'sign-in': return await teamSignIn(deps, words)
case 'remove': return await remove(deps, json)
case 'on': return await teamOn(deps, json, flags.includes('--yes'))
case 'off': return await teamOff(deps, json, flags)
@@ -300,172 +263,16 @@ function byHandLines({ layout, mac, windows }: TeamHere, owner: string, ownerHom
]
}
-const notMac = 'The Harness Team account is made on a Mac, a Linux or a Windows computer. On a computer used only for agents, run `harness team on`.'
-
-/** Why the Linux setup script stopped before it made anything, by the code `harness team setup --json` answers. */
-const LINUX_REFUSALS: ReadonlyMap<string, string> = new Map([[LINUX_NO_SYSTEMD, 'NO_SYSTEMD'], [LINUX_NO_TMUX, 'NO_TMUX']])
/** A script's reason as a sentence, so the one after it does not run on: the scripts' own reasons end without a stop. */
const sentence = (text: string): string => /[.!?]$/.test(text) ? text : `${text}.`
-/** The Windows setup script's exit when Windows will make no local account here (a domain or Entra policy). */
-const WINDOWS_NO_LOCAL_ACCOUNTS = 5
-/** How many times Task Scheduler is asked to start the team task, a second apart, as launchctl bootstrap is on a Mac. */
-const TASK_START_TRIES = 5
-/**
- * Windows, after the elevated script and as the owner: the sign-in, then the team daemon's task. Here and not in the
- * script, because UAC may run that as another administrator, whose `team __handoff` would sign in the wrong person; and
- * after the prompt, so the code's 90 seconds start once the person has answered it. A sign-in is handed over when the
- * account has none that worked (its status file says), or when asked again. The code waits in the handover folder
- * (./windowsLayout.ts), which the team daemon reads and empties as it starts (`team __start`).
- */
-async function windowsHandOver(deps: TeamCommandDeps, layout: TeamLayout, signInAgain: boolean): Promise<{ handedOver: boolean } | { failed: string }> {
- let handedOver = false
- let noSignIn: string | null = null
- deps.progress?.('sign-in')
- if (signInAgain || deps.readStatus(layout.statusFile)?.signIn?.state !== 'signed-in') {
- try {
- const { code } = await mintTeamHandoff(() => deps.auth(), deps.post)
- if (!deps.handOver) throw new Error('nothing here can hand it over')
- deps.handOver(code)
- handedOver = true
- } catch (error) {
- noSignIn = `could not hand a sign-in to the team account (${(error as Error).message})`
- }
- }
- // Started whether or not a code went over, as the Mac's script starts its daemon: with the sign-in it had, or none.
- deps.progress?.('daemon')
- for (let tries = 1; ; tries++) {
- if (await deps.startTeamTask?.()) break
- if (tries >= TASK_START_TRIES) return { failed: `Task Scheduler would not start the team daemon's task ${layout.service.label}` }
- await deps.sleep(1_000)
- }
- if (noSignIn) return { failed: `${noSignIn}; the team daemon runs without a new sign-in` }
- return { handedOver }
-}
-
-async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean): Promise<number> {
- const here = teamHere(deps.platform)
- if (!here) return fail(deps, json, 'UNSUPPORTED', notMac)
- const { layout, scripts, mac, windows } = here
- if (deps.uid() === 0) {
- return fail(deps, json, 'RUN_AS_YOURSELF', `Run this as yourself, not with sudo: ${mac ? 'macOS' : 'Harness'} asks for an administrator password itself.`)
- }
- const session = deps.session()
- if (!session) return fail(deps, json, 'NOT_SIGNED_IN', 'Sign this computer in first (harness login): the team account is signed in from your sign-in.')
- if (session.kind === 'team') return fail(deps, json, 'TEAM_SESSION', 'This computer already runs team work only (harness team on): it needs no Harness Team account.')
- // From the owner's own process, before any prompt: on Windows the profile path is the owner's USERPROFILE (a Microsoft
- // account's folder is not named after the account), and UAC may run the elevated script as another administrator.
- const owner = userCheck(deps.platform)(deps.user(), 'owner account')
- const ownerHome = pathCheck(deps.platform)(deps.home(), 'home folder')
- if (owner.toLowerCase() === TEAM_USER) return fail(deps, json, 'RUN_AS_YOURSELF', 'Run this from your own account, not the Harness Team account.')
- let ownerSid: string | undefined
- if (windows) {
- const sid = await deps.ownerSid?.()
- if (!sid) return fail(deps, json, 'NO_OWNER_SID', 'Could not read this account\'s SID (whoami /user), which setup names you by. Nothing was changed.')
- ownerSid = checkSid(sid, 'owner account')
- }
- const installed = deps.installed()
- if (!deps.exists(installed.cliJs) || !installed.nodeRuntimeDir) {
- return fail(deps, json, 'NOT_INSTALLED', 'Harness is not installed for this account (no ~/.harness/cli/cli.js and Node runtime to copy). Install it, then run this again.')
- }
- const carried = carriedBackendEnv(deps.env)
- const mintEnv: Record<string, string> = { ...carried }
- if (deps.env.HARNESS_AUTH_DIR?.trim()) mintEnv.HARNESS_AUTH_DIR = pathCheck(deps.platform)(deps.env.HARNESS_AUTH_DIR.trim(), 'HARNESS_AUTH_DIR')
- delete mintEnv.ADAPTER_UPDATE_DISABLE
- const sep = windows ? '\\' : '/'
- const nodeName = installed.nodeRuntimeDir.slice(installed.nodeRuntimeDir.lastIndexOf(sep) + 1)
- // Windows' Node runtime keeps node.exe at its top, not in bin/.
- const team = windows ? windowsTeamPaths(layout.home) : teamPaths(layout.home)
- const teamNode = windows ? `${team.runtime}\\${nodeName}\\node.exe` : `${team.runtime}/${nodeName}/bin/node`
- // Windows lays the CLI down in version folders, as the owner's install does: the owner's version now (the config names
- // its cli.js), and the task runs whichever one `cli\current` names when it starts (./windowsScript.ts teamTaskXml).
- const teamCli = windows ? `${team.cli}\\${installed.cliDir.slice(installed.cliDir.lastIndexOf('\\') + 1)}\\cli.js` : team.cliJs
- const serviceCli = windows ? team.cli : team.cliJs
- const config: TeamConfig = {
- version: 1, user: TEAM_USER, realName: TEAM_REAL_NAME, home: layout.home, owner, ownerHome, ...ownerSid ? { ownerSid } : {},
- sentinel: `${ownerHome}${sep}${SENTINEL_NAME}`, port: TEAM_PORT, label: layout.service.label, plist: layout.service.file,
- statusFile: layout.statusFile, node: teamNode, cli: teamCli, env: carried, createdAt: new Date(deps.now()).toISOString(),
- }
- const service = scripts.service({ user: TEAM_USER, home: layout.home, node: teamNode, cli: serviceCli, port: TEAM_PORT, env: carried,
- ...ownerSid ? { ownerSid } : {} })
- const repair = deps.readConfig() !== null || await deps.accountExists(TEAM_USER)
- // Linux: sudo in a terminal, which works over SSH too; polkit's dialog otherwise (Desktop's offer), when there is a desktop.
- // Windows: User Account Control, always.
- const via: AdminVia | undefined = mac ? undefined : windows ? 'prompt' : deps.interactive ? 'sudo' : 'prompt'
- if (!json) {
- const asks = mac ? 'macOS asks for an administrator password once.'
- : windows ? 'Windows asks for permission once (User Account Control).'
- : via === 'sudo' ? 'sudo asks for your password here.' : 'Your system asks for your password once.'
- deps.out(repair
- ? `Harness will repair the Harness Team account on ${here.where}. ${asks}`
- : `Harness will set up a separate account for Swarm work on ${here.where}. ${asks}`)
- for (const line of madeLines(here, owner, ownerHome)) deps.out(line)
- }
- const startedAt = deps.now()
- const asked = prompts(here.where)
- deps.progress?.('password')
- const result = await deps.admin((stageDir) => ({
- script: scripts.setup({
- user: TEAM_USER, realName: TEAM_REAL_NAME, home: layout.home, owner, ownerHome, stageDir,
- nodeRuntimeDir: installed.nodeRuntimeDir!, tmuxRuntimeDir: installed.tmuxRuntimeDir, cliDir: installed.cliDir,
- ownerNode: installed.node, ownerCli: installed.cliJs, mintEnv, signIn: signInAgain ? 'always' : 'missing',
- ...mac && installed.engineCopies?.length ? { engineCopies: installed.engineCopies } : {},
- ...windows ? { ownerSid, ptyDir: installed.ptyDir ?? null } : {},
- }),
- files: { 'team.json': teamConfigJson(config), [scripts.serviceFile]: service },
- }), repair ? asked.repair : asked.setup, via, (step) => deps.progress?.(step))
- if (!result.ok) {
- if (result.code === 'CANCELLED') return fail(deps, json, 'CANCELLED', 'Nothing was changed: the administrator prompt was cancelled.')
- if (result.code === 'NO_PROMPT') return fail(deps, json, 'NO_PROMPT', result.message)
- const refusal = result.status === 3 ? LINUX_REFUSALS.get(result.message)
- : windows && result.status === WINDOWS_NO_LOCAL_ACCOUNTS ? 'NO_LOCAL_ACCOUNTS' : undefined
- if (refusal) return fail(deps, json, refusal, `The Harness Team account was not set up: ${sentence(result.message)} Nothing was changed.`)
- return fail(deps, json, 'SETUP_FAILED', `The Harness Team account was not finished: ${sentence(result.message)} Run \`harness team setup\` again; it repairs what is there.`)
- }
- try { deps.setupDecision?.clear() } catch { /* only Desktop's offer reads it */ }
- let handedOver = /handed a sign-in to the team account/.test(result.stdout)
- if (windows) {
- const handOver = await windowsHandOver(deps, layout, signInAgain)
- if ('failed' in handOver) {
- return fail(deps, json, 'SETUP_FAILED', `The Harness Team account was not finished: ${sentence(handOver.failed)} Run \`harness team setup\` again; it repairs what is there.`)
- }
- handedOver = handOver.handedOver
- }
- deps.progress?.('report')
- if (!json) deps.out(handedOver ? 'Waiting for the team daemon to sign in and check its privacy…' : 'Waiting for the team daemon to check its privacy…')
- // The daemon reports through its status file (./privacy.ts): the sign-in when it redeemed one, the check every start.
- let report: TeamStatus | null = null
- // From now, not from before the prompt: a person may take longer than this to answer it.
- const deadline = deps.now() + SETUP_REPORT_WAIT_MS
- for (;;) {
- report = deps.readStatus(layout.statusFile)
- const checked = (report?.privacy?.checkedAt ?? 0) >= startedAt
- const signed = !handedOver || (report?.signIn?.at ?? 0) >= startedAt
- if ((checked && signed) || deps.now() >= deadline) break
- await deps.sleep(1_000)
- }
- const privacy = report?.privacy && report.privacy.checkedAt >= startedAt ? report.privacy : null
- const signIn = report?.signIn && (!handedOver || report.signIn.at >= startedAt) ? report.signIn : null
- const engines = report?.engines && report.engines.checkedAt >= startedAt ? report.engines : undefined
- if (json) {
- const ok = privacy?.passed === true && (!handedOver || signIn?.state === 'signed-in')
- deps.out(JSON.stringify({ ok, user: TEAM_USER, home: layout.home, label: layout.service.label, plist: layout.service.file, privacy, signIn,
- engines: engines ?? null }))
- return ok ? 0 : 1
- }
- let code = 0
- if (handedOver && signIn?.state === 'signed-in') deps.out('✓ The Harness Team account is signed in.')
- else if (handedOver && signIn) { deps.err(`✗ The team account did not sign in: ${signIn.detail ?? signIn.state}`); code = 1 }
- else if (handedOver) deps.out('! The team daemon has not signed in yet: harness team status')
- if (privacy?.passed) deps.out('✓ Private: the team account cannot read your files.')
- else if (privacy) { deps.err(`✗ Not private (${privacy.item}): ${privacy.detail}`); code = 1 }
- else deps.out('! The team daemon has not reported its privacy check yet: harness team status')
- // Installed by setup into the team account's own home; signed in once by the owner, in a terminal on the team machine.
- for (const line of engineLines(engines, (at) => ago(deps.now(), at), deps.platform)) deps.out(line)
- deps.out(' status: harness team status · undo: harness team remove')
- return code
+/** Swarm v3 has no Team accounts (anh Dee, 2026-11-07): nothing makes one, signs its engines in or gives it a model now.
+ * `harness team remove` deletes one made before. */
+function removed(deps: TeamCommandDeps, json: boolean): number {
+ return fail(deps, json, 'TEAM_ACCOUNTS_REMOVED', 'Swarm v3 has no Team accounts: Swarm work runs in your own account. '
+ + 'To delete one made before: harness team remove.')
}
function ago(now: number, at: number): string {
@@ -484,7 +291,7 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
if (!here || (!config && !exists)) {
if (json) deps.out(JSON.stringify({ account: false, dedicated }))
else if (dedicated) deps.out('This computer runs team work only (harness team on): Swarm agents run here, and it reaches none of your other computers.\n undo: harness team off')
- else deps.out(`No Harness Team account on this computer.${here ? ' harness team setup makes one.' : ' On a computer used only for agents: harness team on.'}`)
+ else deps.out(`No Harness Team account on this computer.${here ? '' : ' On a computer used only for agents: harness team on.'}`)
return 0
}
const { layout } = here
@@ -512,8 +319,9 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
}
const now = deps.now()
deps.out(`Harness Team account · ${config?.realName ?? TEAM_REAL_NAME} (${user})`)
- deps.out(` account ${exists ? '● exists' : '○ missing · harness team setup makes it again'}`)
- deps.out(` daemon ${job.pid !== null ? `● running (pid ${job.pid})` : job.loaded ? `◍ loaded, not running${job.state ? ` (${job.state})` : ''}` : plistPresent ? '○ installed, not loaded · harness team setup starts it' : '○ not installed · harness team setup installs it'}`)
+ deps.out(' Swarm v3 has no Team accounts: its daemon stops once no agent runs in it. harness team remove deletes the account, its home and its daemon.')
+ deps.out(` account ${exists ? '● exists' : '○ missing'}`)
+ deps.out(` daemon ${job.pid !== null ? `● running (pid ${job.pid})` : job.loaded ? `◍ loaded, not running${job.state ? ` (${job.state})` : ''}` : plistPresent ? '○ installed, stopped · harness team remove removes it' : '○ not installed · harness team remove removes what is left'}`)
const signIn = report?.signIn
deps.out(` sign-in ${!signIn ? '? not reported yet' : signIn.state === 'signed-in' ? `✓ signed in (${ago(now, signIn.at)})` : `✗ ${signIn.state}${signIn.detail ? `: ${signIn.detail}` : ''}`}`)
const privacy = report?.privacy
@@ -524,14 +332,13 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
|| (deps.platform === 'linux' && homeMode !== null && (homeMode & 0o007) === 0 && privacy?.passed === true)
// Windows has no mode bits to show: an ACL keeps the profile private, and the privacy check is what proves it.
deps.out(here.windows
- ? ` your home ${ownerHome} · ${privacy?.passed ? 'private ✓' : '? not proven private yet: the privacy check says why; harness team setup takes broad access off it again'}`
- : ` your home ${ownerHome} · mode ${homeMode === null ? 'unknown' : homeMode.toString(8)}${homePrivate ? ' ✓' : ' ✗ should be 700: harness team setup makes it private again'}`)
+ ? ` your home ${ownerHome} · ${privacy?.passed ? 'private ✓' : '? not proven private yet: the privacy check says why; harness team remove takes broad access off it'}`
+ : ` your home ${ownerHome} · mode ${homeMode === null ? 'unknown' : homeMode.toString(8)}${homePrivate ? ' ✓' : ' ✗ should be 700: harness team remove makes it private'}`)
if (agentTmp) {
deps.out(` temp files ${agentTmp.path} · ${agentTmp.state === 'not-made' ? 'made when your next agent starts'
: agentTmp.state === 'private' ? 'mode 700 ✓'
: `${agentTmp.mode === null ? 'not a private folder' : `mode ${agentTmp.mode.toString(8)}`} ✗ your agents may use the shared /tmp: your next agent makes it private, or says why not in the daemon's log`}`)
}
- for (const line of engineLines(report?.engines, (at) => ago(now, at), deps.platform)) deps.out(line)
for (const line of purgeLines(report?.purges, (at) => ago(now, at))) deps.out(line)
deps.out('')
deps.out(' What setup made:')
@@ -645,7 +452,6 @@ async function remove(deps: TeamCommandDeps, json: boolean): Promise<number> {
}
return fail(deps, json, 'REMOVE_FAILED', `The Harness Team account was not fully removed: ${sentence(result.message)} Run \`harness team remove\` again.`)
}
- try { deps.setupDecision?.decline() } catch { /* only Desktop's offer reads it */ }
const forgotten = await forgetTeamComputer(deps)
if (json) {
deps.out(JSON.stringify({ ok: true, removed: true, computer: forgotten }))
@@ -660,7 +466,6 @@ async function remove(deps: TeamCommandDeps, json: boolean): Promise<number> {
const later = result.stdout.split('\n').find((line) => line.includes('is removed at the next restart'))
if (later) deps.out(` ${later.replace(/^harness: /, '').trim()}.`)
deps.out(windows ? ' Your profile stays private.' : ' Your home folder stays private (mode 700).')
- deps.out(' Harness will not make it again on its own when you join a Swarm; harness team setup makes it again.')
return 0
}
@@ -795,7 +600,7 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promis
}
const label = `${deps.hostname().slice(0, 60)} · Team`
if (mine && deps.session()?.kind !== 'team') {
- report({ signIn: { state: 'signed-out', at: deps.now(), detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' } })
+ report({ signIn: { state: 'signed-out', at: deps.now(), detail: 'The Team sign-in is no longer available.' } })
}
if (file) {
let code: string | null = null
@@ -861,7 +666,7 @@ const quoted = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
async function teamLogs(deps: TeamCommandDeps, words: readonly string[], flags: readonly string[], json: boolean): Promise<number> {
const where = deps.platform === 'darwin' ? 'this Mac' : 'this computer'
const config = deps.readConfig()
- if (!config) return fail(deps, json, 'NO_ACCOUNT', `No Harness Team account on ${where}. Run harness team setup first.`)
+ if (!config) return fail(deps, json, 'NO_ACCOUNT', `No Harness Team account on ${where}.`)
const inline = flags.find((flag) => flag.startsWith('--lines='))
const asked = inline ? Number(inline.slice('--lines='.length)) : flags.includes('--lines') ? Number(words[1]) : 40
const lines = Number.isInteger(asked) && asked > 0 && asked <= 5000 ? asked : 40
@@ -880,37 +685,3 @@ async function teamLogs(deps: TeamCommandDeps, words: readonly string[], flags:
deps.out(result.stdout.replace(/\n$/, ''))
return 0
}
-
-/**
- * `harness team sign-in [claude|codex]`: the vendor's own sign-in as the team account, in the terminal the person is
- * already in. On a server there is no Harness app to open a terminal on that account (headless run, 2026-11-03).
- */
-async function teamSignIn(deps: TeamCommandDeps, words: readonly string[]): Promise<number> {
- const where = deps.platform === 'darwin' ? 'this Mac' : 'this computer'
- const config = deps.readConfig()
- if (!config) return fail(deps, false, 'NO_ACCOUNT', `No Harness Team account on ${where}. Run harness team setup first.`)
- if (deps.platform === 'win32') {
- deps.err('✗ On Windows, sign in from Harness: harness team status shows the command for that account.')
- return 1
- }
- if (!deps.interactive) {
- deps.err('✗ Run it in a terminal: the engine asks its questions there.')
- return 1
- }
- const asked = words[1]
- if (asked && asked !== 'claude' && asked !== 'codex') {
- deps.err('✗ Name claude or codex: harness team sign-in claude')
- return 1
- }
- const engine = asked ?? 'claude'
- const command = engine === 'claude' ? 'claude' : 'codex login --device-auth'
- deps.out(`Signing ${engine === 'claude' ? 'Claude Code' : 'Codex'} in as ${config.user} (the Harness Team account)...`)
- const result = spawnSync('sudo', ['-u', config.user, '-H', 'bash', '-lc', command], { stdio: 'inherit' })
- if (result.status === 0) {
- deps.out('Signed in. harness team status shows it.')
- return 0
- }
- deps.err('✗ The sign-in did not finish.')
- return 1
-}
-
diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.ts
index 9fbf48e5a..7773da787 100644
--- a/cli/src/team/deps.ts
+++ b/cli/src/team/deps.ts
@@ -27,7 +27,6 @@ import { agentTmpState } from '../lib/agentTmp.js'
import { realPrivacyDeps, readTeamStatus, runPrivacyCheck, writeTeamStatus } from './privacy.js'
import { takeHandoffFile } from './handoff.js'
import { checkTeamEngines, ownerEngineCopies, realEngineCheckDeps } from './engines.js'
-import { teamSetupDecisionFile, writeTeamSetupDecision } from './autoSetup.js'
/** What `launchctl print system/<label>` says of a job; not loaded when launchd does not know it. Readable without root. */
export function parseLaunchctlPrint(code: number | null, stdout: string): JobState {
@@ -154,10 +153,6 @@ export function teamCommandDeps(options: {
takeHandoff: (path) => process.platform === 'win32' ? takeWindowsHandoffFile(path) : takeHandoffFile(path),
privacy: (config) => runPrivacyCheck(config, realPrivacyDeps),
engines: (config) => checkTeamEngines(realEngineCheckDeps(config.home)),
- setupDecision: {
- clear: () => writeTeamSetupDecision(teamSetupDecisionFile(env.ADAPTER_DATA_DIR), null),
- decline: () => writeTeamSetupDecision(teamSetupDecisionFile(env.ADAPTER_DATA_DIR), { state: 'declined', at: Date.now() }),
- },
stopDaemon: options.stopDaemon,
startDaemon: options.startDaemon,
...(options.signIn ? { signIn: options.signIn } : {}),
diff --git a/cli/src/team/engines.spec.ts b/cli/src/team/engines.spec.ts
index 22aefd750..db08566bb 100644
--- a/cli/src/team/engines.spec.ts
+++ b/cli/src/team/engines.spec.ts
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { readTeamConfig, type TeamConfig } from './config.js'
-import { checkTeamEngines, engineLines, ownerEngineCopies, realEngineCheckDeps, teamEngineBin, teamEngineReporter, TeamEngineReporter, type TeamEngines } from './engines.js'
+import { checkTeamEngines, ownerEngineCopies, realEngineCheckDeps, teamEngineBin, teamEngineReporter, TeamEngineReporter, type TeamEngines } from './engines.js'
import { readTeamStatus, type TeamStatus } from './privacy.js'
vi.mock('./config.js', async (original) => ({ ...await original<typeof import('./config.js')>(), readTeamConfig: vi.fn(() => null) }))
@@ -62,37 +62,6 @@ describe('the team account\'s engines', () => {
expect(result.claude.installed).toBe(false)
})
- it('are said plainly in status, with exactly how to sign in the ones that are not', () => {
- const ago = (at: number) => `${at}s ago`
- const lines = engineLines(engines({ claude: { installed: true, signedIn: false }, codex: { installed: false, signedIn: null } }), ago).join('\n')
- expect(lines).toContain('Claude Code ✓ installed · ✗ not signed in')
- expect(lines).toContain('Codex ✗ not installed · harness team setup installs it')
- expect(lines).toContain('open a terminal on this Mac\'s Harness Team machine')
- // Off a Mac the computer is not a Mac (seen in `harness team setup` on Linux, 2026-10-28).
- const linux = engineLines(engines({ claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: false } }), ago, 'linux').join('\n')
- expect(linux).toContain('open a terminal on this computer\'s Harness Team machine')
- expect(linux).not.toContain('Mac')
- // A computer used over a terminal has no Harness app to open a terminal in (headless run, 2026-11-03): the same
- // sign-in, from the terminal the person is already in.
- expect(linux).toContain('Or from a terminal on this computer, as harnessteam:')
- expect(linux).toContain('sudo -u harnessteam -H bash -lc claude')
- expect(lines).toContain('Or from a terminal on this Mac, as harnessteam:')
- // Windows has no sudo: its sign-in stays the Harness terminal's.
- expect(engineLines(engines({ claude: { installed: true, signedIn: false } }), ago, 'win32').join('\n')).not.toContain('sudo -u')
- // Nothing is lent: the owner's subscription is never used for the account (task #4137).
- expect(linux).not.toContain('nothing to lend')
- expect(lines).toContain(' claude Claude Code')
- expect(lines).not.toContain('codex login')
- expect(lines).toContain('Your own sign-ins are not copied into the team account')
- const unknown = engineLines(engines({ codex: { installed: true, signedIn: null } }), ago).join('\n')
- expect(unknown).toContain('Codex ✓ installed · ? sign-in unknown')
- expect(unknown).toContain(' codex login --device-auth Codex')
- const ready = engineLines(engines(), ago).join('\n')
- expect(ready).toContain('✓ installed · ✓ signed in')
- expect(ready).toContain('(checked 1000s ago)')
- expect(ready).not.toContain('To sign')
- expect(engineLines(undefined, ago)).toEqual([' engines ? not reported yet: the team daemon reports them once it runs'])
- })
})
describe('TeamEngineReporter', () => {
diff --git a/cli/src/team/engines.ts b/cli/src/team/engines.ts
index 1c2953fc1..c2d20afa1 100644
--- a/cli/src/team/engines.ts
+++ b/cli/src/team/engines.ts
@@ -17,7 +17,6 @@ import { engineAccount, type EngineAccount } from '../lib/engineAccount.js'
import { env } from '../config/env.js'
import { readTeamConfig, type TeamConfig } from './config.js'
import { receiveTeamModel } from './modelHandoff.js'
-import { TEAM_USER } from './layout.js'
import type { EngineCopy } from './script.js'
import { readTeamStatus, writeTeamStatus, type TeamStatus } from './privacy.js'
@@ -227,37 +226,3 @@ export function teamEngineReporter(): TeamEngineReporter {
report: (update) => writeTeamStatus(config.statusFile, update) }) } : {}),
})
}
-
-/** What `harness team status` and setup say of the engines, and exactly how to sign them in, on [platform]'s computer. */
-export function engineLines(engines: TeamEngines | undefined, ago: (at: number) => string, platform: NodeJS.Platform = 'darwin'): string[] {
- const computer = platform === 'darwin' ? 'this Mac' : 'this computer'
- if (!engines) {
- return [' engines ? not reported yet: the team daemon reports them once it runs']
- }
- const lines = TEAM_ENGINES.map(({ engine, name }, index) => {
- const e = engines[engine]
- const state = !e.installed ? '✗ not installed · harness team setup installs it'
- : e.signedIn === true ? '✓ installed · ✓ signed in'
- : e.signedIn === false ? '✓ installed · ✗ not signed in' : '✓ installed · ? sign-in unknown'
- return ` ${index === 0 ? 'engines' : ' '} ${name.padEnd(12)}${state}`
- })
- lines.push(` (checked ${ago(engines.checkedAt)})`)
- const unsigned = TEAM_ENGINES.filter(({ engine }) => engines[engine].installed && engines[engine].signedIn !== true)
- if (unsigned.length) {
- lines.push('', ` To sign the team account's engines in, once: in Harness, open a terminal on ${computer}'s Harness Team machine`,
- ' (it is listed among your machines), and run there:')
- for (const { name, signIn } of unsigned) lines.push(` ${signIn.padEnd(28)}${name}`)
- // A computer used over a terminal has no Harness app to open a terminal in (headless run, 2026-11-03): the same sign-in,
- // from the terminal the person is already in.
- if (platform !== 'win32') {
- lines.push(` Or from a terminal on ${computer}, as ${TEAM_USER}:`)
- const terminal = unsigned.map(({ engine, name }) => ({
- command: `sudo -u ${TEAM_USER} -H bash -lc ${engine === 'claude' ? 'claude' : "'codex login --device-auth'"}`, name,
- }))
- const width = Math.max(...terminal.map(({ command }) => command.length)) + 3
- for (const { command, name } of terminal) lines.push(` ${command.padEnd(width)}${name}`)
- }
- lines.push(' Your own sign-ins are not copied into the team account; each engine bills the account you sign in with.')
- }
- return lines
-}
diff --git a/cli/src/team/model.spec.ts b/cli/src/team/model.spec.ts
deleted file mode 100644
index 787461817..000000000
--- a/cli/src/team/model.spec.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-import { buildModelScript, teamModelSet, MODEL_USAGE } from './model.js'
-import type { TeamCommandDeps } from './command.js'
-
-const config = { user: 'harnessteam', home: '/home/harnessteam', node: '/home/harnessteam/.harness/runtime/node/bin/node', label: 'harness-team.service' }
-
-function setup(over: Record<string, unknown> = {}) {
- const out: string[] = [], errors: string[] = [], built: Array<{ script: string; files: Record<string, string> }> = []
- const admin = vi.fn(async (build: (stage: string) => { script: string; files?: Record<string, string> }) => {
- built.push(build('/stage') as { script: string; files: Record<string, string> })
- return { ok: true as const, stdout: 'done' }
- })
- const deps = {
- platform: 'linux', out: (line: string) => out.push(line), err: (line: string) => errors.push(line),
- interactive: true, uid: () => 501, readConfig: () => config, admin,
- askSecret: async () => 'sk-test-key', ask: async () => 'sk-test-key', ...over,
- } as unknown as TeamCommandDeps
- return { deps, out, errors, built, admin }
-}
-
-describe('harness team model set', () => {
- it('saves the key as a saved API and the engine settings, and says it in two lines', async () => {
- const f = setup()
- expect(await teamModelSet(f.deps, ['model', 'set', 'openrouter', 'deepseek/deepseek-v4.1-flash-1017'], ['--model'])).toBe(0)
- expect(f.admin).toHaveBeenCalledTimes(1)
- const [{ script, files }] = f.built
- expect(script).toContain('api-connections/connections.json')
- expect(script).toContain('systemctl restart')
- expect(files['connections.json']).toContain('"apiKey":"sk-test-key"')
- expect(files['model.json']).toContain('"ANTHROPIC_BASE_URL":"https://openrouter.ai/api"')
- expect(f.out.join('\n')).toContain('now runs Claude Code on OpenRouter · deepseek/deepseek-v4.1-flash-1017')
- expect(f.out.join('\n')).not.toContain('sk-test-key')
- })
-
- it('refuses without a key, a model, a known provider, or an account, and never on Windows', async () => {
- const noModel = setup()
- expect(await teamModelSet(noModel.deps, ['model', 'set', 'openrouter'], [])).toBe(1)
- expect(noModel.errors.join('\n')).toContain('--model is needed')
- const unknown = setup()
- expect(await teamModelSet(unknown.deps, ['model', 'set', 'nope'], ['--model', 'x'])).toBe(1)
- expect(unknown.errors.join('\n')).toContain('Unknown provider')
- const anthropic = setup()
- expect(await teamModelSet(anthropic.deps, ['model', 'set', 'anthropic'], ['--model', 'claude'])).toBe(1)
- const bare = setup({ readConfig: () => null })
- expect(await teamModelSet(bare.deps, ['model', 'set', 'openrouter'], ['--model', 'x'])).toBe(1)
- expect(bare.errors.join('\n')).toContain('Run harness team setup first')
- })
-
- describe('on Windows', () => {
- const windows = (status: () => unknown, over = {}) => {
- let clock = 1_000
- const handed: unknown[] = []
- const f = setup({ platform: 'win32', handModel: (h: unknown) => handed.push(h), now: () => clock, sleep: async (ms: number) => { clock += ms }, readStatus: status, ...over })
- return { ...f, handed }
- }
-
- it('leaves it for the Team account, with no administrator prompt, and waits until it says so', async () => {
- let looks = 0
- const f = windows(() => ++looks < 3 ? null : { version: 1, model: { state: 'applied', at: 1_000 } })
- expect(await teamModelSet(f.deps, ['model', 'set', 'openrouter', 'm1'], ['--model'])).toBe(0)
- expect(f.admin).not.toHaveBeenCalled()
- expect(JSON.stringify(f.handed)).toContain('sk-test-key')
- expect(f.out.join('\n')).not.toContain('sk-test-key')
- expect(f.out.join('\n')).toContain('now runs Claude Code on OpenRouter')
- })
-
- it('says why when the Team account could not take it, or is not running', async () => {
- const refused = windows(() => ({ version: 1, model: { state: 'failed', at: 1_000, detail: 'disk full' } }))
- expect(await teamModelSet(refused.deps, ['model', 'set', 'openrouter', 'm1'], ['--model'])).toBe(1)
- expect(refused.errors.join('\n')).toContain('disk full')
- const quiet = windows(() => ({ version: 1, model: { state: 'applied', at: 1 } }))
- expect(await teamModelSet(quiet.deps, ['model', 'set', 'openrouter', 'm1'], ['--model'])).toBe(1)
- expect(quiet.errors.join('\n')).toContain('did not take it yet')
- })
- })
-
- it('clears it again, and never asks for a key to do so', async () => {
- const asked = vi.fn(async () => 'never')
- const f = setup({ askSecret: asked })
- expect(await teamModelSet(f.deps, ['model', 'set'], ['--clear'])).toBe(0)
- expect(asked).not.toHaveBeenCalled()
- expect(f.built[0]!.script).toContain('rm -f "$DATA/api-connections/connections.json"')
- expect(f.out.join('\n')).toContain('has no model API again')
- })
-
- it('keeps the usage short enough to read', () => {
- expect(MODEL_USAGE.split('\n').length).toBeLessThan(12)
- expect(MODEL_USAGE).toContain('hidden prompt')
- })
-})
diff --git a/cli/src/team/model.ts b/cli/src/team/model.ts
deleted file mode 100644
index 997df5d5b..000000000
--- a/cli/src/team/model.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * `harness team model set …`: the Harness Team account's own model API, for a computer whose owner has no subscription
- * for the relay to lend, or wants another model. The key is asked for here, hidden, and never reaches a command line.
- *
- * It writes the four things a person would otherwise edit by hand: the saved API (Models ▸ APIs) in the team account's
- * data folder, the engine's base URL, token and model in its Claude settings, and a restart of its daemon.
- */
-import { API_PRESETS, servesModels } from '../lib/apiConnections.js'
-import type { TeamCommandDeps } from './command.js'
-import { teamPaths } from './layout.js'
-import { writeModelHandoff, type TeamModelHandoff } from './modelHandoff.js'
-
-export const MODEL_USAGE = [
- 'Usage: harness team model set <provider> --model <model-id> [--key-stdin] [--clear]',
- '',
- ' <provider> openrouter, openai, anthropic, requesty, fal, replicate, or custom with --base-url <url>',
- ' --model the model id that provider serves, e.g. deepseek/deepseek-v4.1-flash-1017',
- ' --key-stdin read the API key from stdin instead of the hidden prompt (for scripts)',
- ' --clear remove it again, back to the owner\'s subscription through the relay',
- '',
- 'The key is asked for here: never printed, never in your shell history.',
-].join('\n')
-
-/** The wide line the hidden prompt leaves behind, and the two lines the command ends with. */
-const DONE = (provider: string, model: string, where: string): string[] => [
- ` ✓ ${where}'s Harness Team account now runs Claude Code on ${provider} · ${model}.`,
- ' Next: harness team status',
-]
-
-interface Chosen { provider: string; name: string; baseUrl: string; keyEnv: string }
-
-function choose(deps: TeamCommandDeps, words: readonly string[], flags: readonly string[]): Chosen | null {
- const provider = words[2]
- if (!provider) { deps.err(MODEL_USAGE); return null }
- if (provider === 'custom') {
- const url = flags.includes('--base-url') ? words[3] : undefined
- if (!url) { deps.err('✗ --base-url is needed with custom (the provider\'s API address, ending in /v1).'); return null }
- return { provider, name: 'Custom', baseUrl: url.replace(/\/+$/, ''), keyEnv: 'CUSTOM_API_KEY' }
- }
- const preset = API_PRESETS.find((row) => row.provider === provider)
- if (!preset) { deps.err(`✗ Unknown provider "${provider}".
-
-${MODEL_USAGE}`); return null }
- return { provider, name: preset.name, baseUrl: preset.baseUrl, keyEnv: preset.keyEnv }
-}
-
-/** `--model <id>` and `--model=<id>`, beside the flags the dispatcher already split out. */
-function modelOf(words: readonly string[], flags: readonly string[]): string | null {
- const inline = flags.find((flag) => flag.startsWith('--model='))
- if (inline) return inline.slice('--model='.length)
- return flags.includes('--model') ? words[3] ?? null : null
-}
-
-function baseUrlOf(words: readonly string[], flags: readonly string[]): string | null {
- const inline = flags.find((flag) => flag.startsWith('--base-url='))
- if (inline) return inline.slice('--base-url='.length)
- return flags.includes('--base-url') ? words[3] ?? null : null
-}
-
-/** The team account's settings.json, with [change] applied: its own env entries and model, or those taken out again. */
-const MERGE = [
- "import { readFileSync, writeFileSync, renameSync, chmodSync } from 'node:fs'",
- 'const [payloadPath, settingsPath, team] = process.argv.slice(2)',
- 'const payload = JSON.parse(readFileSync(payloadPath, "utf8"))',
- 'let settings = {}',
- 'try { settings = JSON.parse(readFileSync(settingsPath, "utf8")) } catch {}',
- 'const env = settings.env && typeof settings.env === "object" ? settings.env : {}',
- 'const keys = payload.clear ? ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"] : Object.keys(payload.env)',
- 'for (const key of keys) delete env[key]',
- 'if (!payload.clear) Object.assign(env, payload.env)',
- 'if (Object.keys(env).length) settings.env = env; else delete settings.env',
- 'if (payload.clear) delete settings.model; else settings.model = payload.model',
- 'const next = settingsPath + ".next"',
- 'writeFileSync(next, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 })',
- 'renameSync(next, settingsPath)',
- 'chmodSync(settingsPath, 0o600)',
-].join('\n')
-
-/** What the root script does: the saved API as the team account, the engine's settings, then its daemon again. */
-export function buildModelScript(input: {
- platform: NodeJS.Platform
- team: string
- home: string
- node: string
- label: string
- stage: string
- clear: boolean
-}): string {
- const data = teamPaths(input.home).data
- const mac = input.platform === 'darwin'
- return [
- '#!/bin/sh',
- '# Harness Team account: its model API (cli/src/team/model.ts), run once as root.',
- 'set -eu',
- 'cd /',
- 'PATH=/usr/sbin:/usr/bin:/sbin:/bin; export PATH',
- `TEAM=${JSON.stringify(input.team)}`,
- `TEAM_HOME=${JSON.stringify(input.home)}`,
- `NODE=${JSON.stringify(input.node)}`,
- `STAGE=${JSON.stringify(input.stage)}`,
- `DATA=${JSON.stringify(data)}`,
- `LABEL=${JSON.stringify(input.label)}`,
- `if [ ! -x "$NODE" ]; then echo "harness: the team account has no Node runtime" >&2; exit 4; fi`,
- 'install -d -o "$TEAM" -m 700 "$DATA/api-connections"',
- input.clear
- ? 'rm -f "$DATA/api-connections/connections.json"'
- : `install -o "$TEAM" -m 600 "$STAGE/connections.json" "$DATA/api-connections/connections.json"`,
- 'mkdir -p "$TEAM_HOME/.claude"',
- '"$NODE" "$STAGE/merge.mjs" "$STAGE/model.json" "$TEAM_HOME/.claude/settings.json" "$TEAM"',
- 'chown "$TEAM" "$TEAM_HOME/.claude/settings.json"',
- 'chmod 600 "$TEAM_HOME/.claude/settings.json"',
- mac
- ? 'launchctl kickstart -k "system/$LABEL" >/dev/null 2>&1 || true'
- : 'systemctl restart "$LABEL" >/dev/null 2>&1 || true',
- 'echo "done"',
- ].join('\n')
-}
-
-/** `harness team model set`: the team account's own model API. */
-/** How long the owner waits for the Team daemon, which looks once a minute (./engines.ts ENGINE_RECHECK_MS). */
-const HANDOVER_WAIT_MS = 90_000
-
-/** Windows: left for the Team daemon, which writes it as itself (./modelHandoff.ts). True once it says it did. */
-async function handOverOnWindows(deps: TeamCommandDeps, statusFile: string, handoff: TeamModelHandoff, json: boolean): Promise<boolean> {
- const startedAt = deps.now()
- try { (deps.handModel ?? writeModelHandoff)(handoff) } catch (error) { deps.err(`✗ ${(error as Error).message}`); return false }
- if (!json) deps.out(' Waiting for the Harness Team account to take it…')
- while (deps.now() - startedAt < HANDOVER_WAIT_MS) {
- const said = deps.readStatus(statusFile)?.model
- if (said && said.at >= startedAt) {
- if (said.state === 'applied') return true
- deps.err(`✗ The Harness Team account could not take it: ${said.detail ?? 'no reason given'}`)
- return false
- }
- await deps.sleep(2_000)
- }
- deps.err('✗ The Harness Team account did not take it yet, so it may not be running. It takes it when it next runs: harness team status shows its state.')
- return false
-}
-
-export async function teamModelSet(deps: TeamCommandDeps, words: readonly string[], flags: readonly string[], json = false): Promise<number> {
- const where = deps.platform === 'darwin' ? 'this Mac' : 'this computer'
- const config = deps.readConfig()
- if (!config) { deps.err(`✗ No Harness Team account on ${where}. Run harness team setup first.`); return 1 }
- const clear = flags.includes('--clear')
- let chosen: Chosen | null = null, model: string | null = null
- if (!clear) {
- chosen = choose(deps, words, flags)
- if (!chosen) return 1
- model = modelOf(words, flags)
- if (!model) { deps.err(`✗ --model is needed: the model id that ${chosen.name} serves.`); return 1 }
- if (!servesModels({ authHeader: 'Authorization', authPrefix: 'Bearer' })) return 1
- if (chosen.provider === 'anthropic') {
- deps.err('✗ Anthropic\'s own API does not fit a Swarm engine. Use openrouter, openai or custom.')
- return 1
- }
- }
- let key = ''
- if (!clear) {
- if (flags.includes('--key-stdin')) key = (await readStdin()).trim()
- else if (!deps.interactive) { deps.err('✗ No terminal to ask for the key. Pipe it: ... | harness team model set … --key-stdin'); return 1 }
- else {
- const question = `Paste the ${chosen!.name} API key: `
- key = (await (deps.askSecret ? deps.askSecret(question) : deps.ask(question))).trim()
- }
- if (!key) { deps.err('✗ No API key was given.'); return 1 }
- }
- const baseUrl = chosen ? (baseUrlOf(words, flags) ?? chosen.baseUrl).replace(/\/+$/, '') : ''
- // Claude reads its endpoint as the API root: OpenRouter's Anthropic-compatible messages live under /api/v1.
- const claudeBase = baseUrl.replace(/\/v1$/, '')
- const connections = JSON.stringify({
- version: 1,
- connections: chosen
- ? [{ id: chosen.provider, provider: chosen.provider, name: chosen.name, baseUrl, keyEnv: chosen.keyEnv,
- authHeader: 'Authorization', authPrefix: 'Bearer', apiKey: key }]
- : [],
- recognizedBases: baseUrl ? [baseUrl] : [],
- })
- const payload = JSON.stringify(chosen
- ? { clear: false, model, env: { ANTHROPIC_BASE_URL: claudeBase, ANTHROPIC_AUTH_TOKEN: key, ANTHROPIC_API_KEY: '' } }
- : { clear: true })
- if (deps.platform === 'win32') {
- if (!await handOverOnWindows(deps, config.statusFile, { connections, payload }, json)) return 1
- if (json) { deps.out(JSON.stringify({ ok: true, provider: chosen?.provider ?? null, model: model ?? null })); return 0 }
- for (const line of clear ? [` ✓ The Harness Team account on ${where} has no model API again.`, ' Next: harness team status']
- : DONE(chosen!.name, model!, where)) deps.out(line)
- return 0
- }
- const result = await deps.admin((stageDir) => ({
- script: buildModelScript({ platform: deps.platform, team: config.user, home: config.home, node: config.node,
- label: config.label, stage: stageDir, clear }),
- files: { 'connections.json': connections, 'model.json': payload, 'merge.mjs': MERGE },
- }), chosen ? `Harness wants to give the Harness Team account on ${where} the model API ${chosen.name}.` : `Harness wants to remove the Harness Team account's model API on ${where}.`)
- if (!result.ok) {
- if (result.code === 'NO_PROMPT') deps.err(`✗ ${result.message} Run it in a terminal.`)
- else if (result.code !== 'CANCELLED') deps.err(`✗ ${result.message}`)
- return 1
- }
- if (json) { deps.out(JSON.stringify({ ok: true, provider: chosen?.provider ?? null, model: model ?? null })); return 0 }
- for (const line of clear ? [` ✓ The Harness Team account on ${where} has no model API again.`, ' Next: harness team status'] : DONE(chosen!.name, model!, where)) deps.out(line)
- return 0
-}
-
-/** The key from stdin, for scripts and for a terminal that cannot hide typing. */
-function readStdin(): Promise<string> {
- return new Promise((resolve) => {
- let text = ''
- process.stdin.setEncoding('utf8')
- process.stdin.on('data', (chunk) => { text += chunk })
- process.stdin.on('end', () => resolve(text))
- process.stdin.on('error', () => resolve(text))
- })
-}
-
diff --git a/cli/src/team/privacy.spec.ts b/cli/src/team/privacy.spec.ts
index dea15c408..9691853c8 100644
--- a/cli/src/team/privacy.spec.ts
+++ b/cli/src/team/privacy.spec.ts
@@ -250,7 +250,7 @@ describe('privacy observer', () => {
signedIn = false
o.observe()
expect(writeStatus).toHaveBeenCalledWith(teamConfig.statusFile, {
- signIn: { state: 'signed-out', at: 7, detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' },
+ signIn: { state: 'signed-out', at: 7, detail: 'The Team sign-in is no longer available.' },
})
const calls = writeStatus.mock.calls.length
o.observe()
@@ -296,7 +296,7 @@ describe('privacy observer', () => {
check: () => ({ passed: true, checkedAt: 7 }), writeStatus: writeTeamStatus, now: () => 7 })
o.observe()
expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ version: 1, privacy: { passed: true, checkedAt: 7 },
- signIn: { state: 'signed-out', at: 7, detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' } })
+ signIn: { state: 'signed-out', at: 7, detail: 'The Team sign-in is no longer available.' } })
})
})
diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.ts
index 642b89a1b..db565ba84 100644
--- a/cli/src/team/privacy.ts
+++ b/cli/src/team/privacy.ts
@@ -305,7 +305,7 @@ export class TeamPrivacyObserver {
if (!signedIn) {
try {
this.deps.writeStatus(config.statusFile, { signIn: { state: 'signed-out', at: now,
- detail: 'The Team sign-in is no longer available. Run harness team setup --sign-in-again.' } })
+ detail: 'The Team sign-in is no longer available.' } })
this.signedIn = signedIn
} catch { /* Try the status write again at the next observation; privacy is checked independently. */ }
} else this.signedIn = signedIn
diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.ts
index cd68d4cb5..a310d6760 100644
--- a/cli/src/team/script.spec.ts
+++ b/cli/src/team/script.spec.ts
@@ -659,7 +659,7 @@ describe('remove script', () => {
it('says so when the team daemon does not start again after a refusal', () => {
const s = sandbox({ refuse: true, bootstrapFails: true })
expect(s.result.status).toBe(REMOVE_REFUSED)
- expect(s.result.stderr).toContain('Nothing was removed, but the team daemon did not start again: harness team setup starts it')
+ expect(s.result.stderr).toContain('Nothing was removed, and the team daemon stays stopped')
expect(s.gone(s.paths.PLIST)).toBe(false)
})
diff --git a/cli/src/team/script.ts b/cli/src/team/script.ts
index b0c3c3bc8..ba8123ade 100644
--- a/cli/src/team/script.ts
+++ b/cli/src/team/script.ts
@@ -668,7 +668,7 @@ export function buildRemoveScript(input: RemoveScriptInput): string {
' launchctl print "system/$LABEL" >/dev/null 2>&1 && again=yes',
' fi',
' case $why in *eDSPermissionError*) why="macOS did not allow it (eDSPermissionError)" ;; esac',
- ` [ "$again" = yes ] || die "could not delete the account $TEAM: $why. Nothing was removed, but the team daemon did not start again: harness team setup starts it" ${REMOVE_REFUSED}`,
+ ` [ "$again" = yes ] || die "could not delete the account $TEAM: $why. Nothing was removed, and the team daemon stays stopped" ${REMOVE_REFUSED}`,
` die "could not delete the account $TEAM: $why. Nothing was removed: the Harness Team account and its daemon run as before" ${REMOVE_REFUSED}`,
' fi',
' say "deleted the account $TEAM"',
@@ -1039,7 +1039,7 @@ export function buildLinuxRemoveScript(input: RemoveScriptInput): string {
' if [ -f "$UNIT" ]; then',
...startAgain,
' fi',
- ` [ "$again" = yes ] || die "could not delete the account $TEAM: $why. Nothing was removed, but the team daemon did not start again: harness team setup starts it" ${REMOVE_REFUSED}`,
+ ` [ "$again" = yes ] || die "could not delete the account $TEAM: $why. Nothing was removed, and the team daemon stays stopped" ${REMOVE_REFUSED}`,
` die "could not delete the account $TEAM: $why. Nothing was removed: the Harness Team account and its daemon run as before" ${REMOVE_REFUSED}`,
' fi',
' say "deleted the account $TEAM"',
diff --git a/cli/src/team/windowsScript.ts b/cli/src/team/windowsScript.ts
index 98c0937cb..83de46d41 100644
--- a/cli/src/team/windowsScript.ts
+++ b/cli/src/team/windowsScript.ts
@@ -998,7 +998,7 @@ export function buildWindowsRemoveScript(input: RemoveScriptInput): string {
' try { Remove-LocalUser -Name $TEAM } catch {',
' Restore-Tasks',
' if ($task) { Enable-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME | Out-Null; Start-ScheduledTask -TaskPath $TASK_PATH -TaskName $TASK_NAME }',
- ` die "could not delete the account $TEAM ($($_.Exception.Message)). Its profile was removed; harness team setup makes it again" ${WINDOWS_REMOVE_REFUSED}`,
+ ` die "could not delete the account $TEAM ($($_.Exception.Message)). Its profile was removed" ${WINDOWS_REMOVE_REFUSED}`,
' }',
' say "deleted the account $TEAM"',
'}',
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index 0ca79f603..b2b98c0e9 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -26,7 +26,6 @@ import 'screens/login_screen.dart';
import 'screens/swarm_menu_bus.dart';
import 'state/app_state.dart';
import 'stats/stats_lifecycle.dart';
-import 'super_tabs/team_account_setup.dart';
import 'viewer/viewer_services.dart';
import 'ws/terminal_transport_plugin.dart';
import 'shared/theme/app_theme.dart' as grid;
@@ -185,7 +184,7 @@ class HarnessApp extends StatelessWidget {
builder: (context, child) {
Widget shell() {
final app = child ?? const SizedBox.shrink();
- final framed = _TeamSetupHold(child: frame?.call(app) ?? app);
+ final framed = frame?.call(app) ?? app;
return _GridTokenScope(
child: keymap == null
? framed
@@ -250,19 +249,6 @@ class _AfterFirstFrameState extends State<_AfterFirstFrame> {
}
}
-/// The whole window, every route and dialog included, waits while this
-/// computer's Harness Team account must be set up after it joined a Swarm
-/// (super_tabs/team_account_setup.dart).
-class _TeamSetupHold extends ConsumerWidget {
- const _TeamSetupHold({required this.child});
-
- final Widget child;
-
- @override
- Widget build(BuildContext context, WidgetRef ref) =>
- TeamAccountSetupLock(app: ref.watch(appStateProvider), child: child);
-}
-
/// Carries Grid's design tokens past this app's `const` chrome.
///
/// A `const` widget is reference-identical across its parent's rebuild, so a
@@ -407,11 +393,7 @@ class _RootShellState extends ConsumerState<RootShell>
/// ([InWindowMenuBar]) fires the same strings directly, so one switch serves
/// every platform.
Future<void> runAppMenuAction(String action) async {
- // The Harness Team account's setup holds the whole window
- // (super_tabs/team_account_setup.dart). AppKit's own Quit and About panel
- // never come here; every action that does waits, the Linux and Windows
- // strip's About included.
- if (!mounted || ref.read(appStateProvider).teamSetupLocked) return;
+ if (!mounted) return;
switch (action) {
case 'settings':
final app = ref.read(appStateProvider);
diff --git a/desktop/lib/core/permission_modes.dart b/desktop/lib/core/permission_modes.dart
index 5df61d35e..749cdd1af 100644
--- a/desktop/lib/core/permission_modes.dart
+++ b/desktop/lib/core/permission_modes.dart
@@ -95,7 +95,7 @@ const Map<String, List<PermissionMode>> kLaunchOnlyPermissionModes = {
PermissionMode(
'teamWritten',
'Full, project settings off',
- 'Runs in a Team account and reads none of the branch\'s own settings',
+ 'Reads none of the branch\'s own settings',
),
],
'codex': [
@@ -107,7 +107,7 @@ const Map<String, List<PermissionMode>> kLaunchOnlyPermissionModes = {
PermissionMode(
'teamWritten',
'Full, project settings off',
- 'Runs in a Team account and reads none of the branch\'s own settings',
+ 'Reads none of the branch\'s own settings',
),
],
};
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 0d6d64c5b..4c454724c 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -87,7 +87,6 @@ import '../super_tabs/launch.dart';
import '../super_tabs/message_link.dart' show swarmMessageLinkInbox;
import '../super_tabs/buddy_chat.dart' show countText;
import '../super_tabs/buddy_chat_shortcut.dart';
-import '../super_tabs/team_account_setup.dart';
import '../super_tabs/workspace.dart';
import '../super_tabs/quick_switcher.dart';
import '../super_tabs/actions.dart';
@@ -328,7 +327,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
bool _deviceRevealInFlight = false;
StreamSubscription<void>? _modelsRequests;
StreamSubscription<String>? _superTabClosures;
- StreamSubscription<String>? _teamSetupAsks;
// The one Swarm notice: whether it exists (queued or shown), whether it
// is on screen, and the closed tab its Reopen restores.
int _superTabNoticeSerial = 0;
@@ -511,9 +509,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// clears first ([_onNative]). A titlebar dropdown is an overlay, not a
/// cover: the titlebar stays as it is, and a click there closes it.
_TitlebarCover get _titlebarCover {
- // The Harness Team account's setup holds the whole window
- // (TeamAccountSetupLock): menus, shortcuts and the row wait with it.
- if (app.teamSetupLocked) return _TitlebarCover.modal;
if (_spokenPaletteOpen) return _TitlebarCover.modal;
if (settingsPageOnTop.value != null) return _TitlebarCover.settingsPage;
if (!_routeIsCurrent || _dialogOpen) return _TitlebarCover.modal;
@@ -906,10 +901,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
});
_superTabClosures = app.superTabClosures.listen(_offerSuperTabReopen);
- // The Harness Team account, explained before macOS asks for the password (super_tabs/team_account_setup.dart).
- _teamSetupAsks = app.teamSetupAsks.listen((_) {
- if (mounted) unawaited(showTeamAccountSetup(context, app, asked: true));
- });
if (!kUnderTest) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
@@ -1066,7 +1057,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.modelManager.setPanelVisible(false);
_modelsRequests?.cancel();
_superTabClosures?.cancel();
- _teamSetupAsks?.cancel();
_keymap.removeListener(_keymapChanged);
_defaultKeymap.dispose();
grid.AppTheme.palette.removeListener(_paletteChanged);
@@ -2501,9 +2491,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// closes every open dropdown first ([dismissTransientMenus]); a row click
/// pops the Settings page first; a modal still drops it ([_actOnNative]).
Future<void> _onNative(MethodCall call) async {
- // Held with the window ([_titlebarCover]): a row or key equivalent that
- // AppKit sent before it greyed out does nothing either.
- if (app.teamSetupLocked) return;
var action = call;
final args = call.arguments is Map ? call.arguments as Map : const {};
// AppKit wraps the row's clicks while its menus are off, which, with the
@@ -5040,11 +5027,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
// Paint hints only; the keymap still owns every shortcut and input event.
_tabShortcutHints.value = showsTabShortcutHints(HardwareKeyboard.instance);
// Off, this is not here at all: every key goes where it went before.
- // Nor while the Harness Team account's setup holds the window
- // (TeamAccountSetupLock): this handler hears keys whatever has focus.
- if (event is! KeyDownEvent ||
- _zoo.daemons == DaemonsSwitch.off ||
- app.teamSetupLocked) {
+ if (event is! KeyDownEvent || _zoo.daemons == DaemonsSwitch.off) {
return false;
}
_noteWindowInput();
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index de249b470..ee0291fdf 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2247,13 +2247,12 @@ class AppNotifier extends ChangeNotifier {
return result;
}
- /// Whether the Harness Team account can be made on this computer's system,
- /// as the offer reads it. Off under test, on a Mac too, unless a test sets
- /// it.
+ /// Whether this computer's system can have a Harness Team account, for
+ /// its join status. Off under test, on a Mac too, unless a test sets it.
@visibleForTesting
bool? teamAccountHereForTest;
- /// The systems the Harness Team account is made on, by
+ /// The systems a Harness Team account was made on, by
/// [RuntimePlatform.operatingSystem]: a Mac, Linux and Windows
/// (cli/src/team/layout.ts; Windows' daemon sets it up behind User Account
/// Control); never a phone, a tablet or a browser.
@@ -2264,372 +2263,8 @@ class AppNotifier extends ChangeNotifier {
teamAccountHereForTest ??
(teamAccountOn(RuntimePlatform.operatingSystem) && !kUnderTest);
- /// How long before asking again a daemon that could not answer the start
- /// offer; each further try waits one more step.
- @visibleForTesting
- Duration teamOfferRetryForTest = const Duration(seconds: 30);
- static const _teamOfferTries = 5;
-
- /// Which daemon process answers this Mac, for a spec; the daemon's own
- /// status otherwise.
- @visibleForTesting
- Future<String?> Function()? daemonIdentityForTest;
- bool _teamOfferBusy = false;
- Timer? _teamOfferRetry;
-
- /// The daemon process the start offer's budget is for, its tries, and
- /// whether it answered. A socket reconnect to the same process keeps them;
- /// only a new process starts over (review of #1790).
- bool _teamOfferStarted = false;
- String? _teamOfferDaemon;
- int _teamOfferTried = 0;
- bool _teamOfferAnswered = false;
- bool _teamStartExplained = false;
-
- /// This Mac's daemon process as its own status says it: its pid and
- /// version, so a restart or an update reads as a new one. Null when it
- /// cannot say.
- Future<String?> _daemonIdentity() async {
- if (daemonIdentityForTest case final read?) return read();
- try {
- final probe = await _discovery.probe();
- return probe.pid == null ? null : '${probe.pid}:${probe.version ?? ''}';
- } catch (_) {
- return null;
- }
- }
-
- /// The Harness Team account on this computer (cli/src/team/autoSetup.ts),
- /// asked of this computer's own daemon while the person is here: as they
- /// join a Swarm ([reason] `join`), add this computer to one (`contribute`),
- /// or open the app (`startup`). On a Mac, Linux and Windows
- /// ([teamAccountOn]), and never for another machine, where nobody may be at
- /// it.
- ///
- /// A join or a contribution with the account missing locks the app until it
- /// exists ([teamSetupLocked]; Scholes, 2026-11-03: Macs that joined stayed
- /// "not set up" until someone found their row in Machines). For a join, a
- /// cancel or a failure the daemon remembers from before locks too: this is
- /// a new join. A contribution locks only while it is wanted or running.
- /// At start the daemon decides (no account, not declined, in a Swarm with
- /// other people), and it is explained once a launch ([teamSetupAsks]),
- /// never behind the lock.
- ///
- /// [tabId]: the Swarm joined or added to, so a Swarm its server does not
- /// try team accounts in yet asks nothing (the daemon reads it), and the lock
- /// knows where Remove this Mac from the Swarm removes it from.
- ///
- /// True when the daemon answered, whatever it decided; false when it was not
- /// asked or could not say.
- Future<bool> offerTeamAccount(String reason, {String? tabId}) async {
- final here = _teamAccountHere();
- if (here == null) return false;
- try {
- final answer = await superTabMachineRequest(here, {
- 'action': 'teamSetupCheck',
- 'reason': reason,
- 'tabId': ?tabId,
- });
- final state = answer['state'];
- appLog.info('super-tabs', 'team account offer ($reason): $state');
- if (reason == 'startup') {
- // The start check runs once for each daemon process, so a restart
- // with the explanation still open must not show it again: once a
- // launch.
- if (state == 'wanted' && !_teamStartExplained && !teamSetupLocked) {
- _teamSetupAsks.add(reason);
- }
- if (state == 'wanted') _teamStartExplained = true;
- } else if (tabId != null &&
- (reason == 'join' ? _teamLockStates : _teamContributeLockStates)
- .contains(state)) {
- await _lockForTeamSetup(tabId);
- }
- return true;
- } catch (error) {
- // An older daemon, or one that cannot say: nothing is asked.
- appLog.info('super-tabs', 'team account not offered ($reason): $error');
- return false;
- }
- }
-
- /// The daemon's answers that leave the account to be made here: wanted, or
- /// held back only by an earlier cancel or failure, already running, or with
- /// no prompt to ask in (the window then says how).
- static const _teamLockStates = {
- 'wanted',
- 'declined',
- 'waiting',
- 'running',
- 'no-prompt',
- };
-
- /// A contribution locks only while the account is to be made now: wanted,
- /// or already running. A cancel or failure the daemon remembers was the
- /// person's answer, and a contribution (settings saved, this Mac added
- /// again) is no new Swarm to ask it again for (Diego, 2026-11-03).
- static const _teamContributeLockStates = {'wanted', 'running'};
-
- /// The Swarms this computer joined, or was added to, while its Harness Team
- /// account was missing, for [_teamLockAccount]. Kept on this computer so a
- /// restart locks again.
- final _teamLockTabs = <String>{};
- String? _teamLockAccount;
- String? _teamLockRestored;
-
- static String _teamLockKey(String account) => 'team_setup_lock.$account';
-
- /// Whether the app is held until this computer's Harness Team account exists
- /// (super_tabs/team_account_setup.dart `TeamAccountSetupLock`).
- bool get teamSetupLocked =>
- _teamLockTabs.isNotEmpty &&
- _teamLockAccount != null &&
- _teamLockAccount == currentUser?.id &&
- _teamAccountHere() != null;
-
- Future<void> _lockForTeamSetup(String tabId) async {
- final account = currentUser?.id;
- if (account == null) return;
- if (_teamLockAccount != account) {
- _teamLockAccount = account;
- _teamLockTabs.clear();
- }
- if (!_teamLockTabs.add(tabId)) return;
- notifyListeners();
- await _saveTeamLock(account);
- }
-
- Future<void> _saveTeamLock(String account) async {
- final store = localStore;
- if (store == null) return;
- try {
- if (_teamLockTabs.isEmpty) {
- await store.delete(_teamLockKey(account));
- } else {
- await store.write(
- _teamLockKey(account),
- jsonEncode(_teamLockTabs.toList()),
- );
- }
- } catch (error) {
- appLog.info('super-tabs', 'team account lock not saved: $error');
- }
- }
-
- /// At each connection of this computer's daemon: a lock left by a join
- /// before the app closed holds again, unless the account exists by now.
- /// Read once for each account.
- Future<void> _restoreTeamSetupLock() async {
- final account = currentUser?.id;
- final store = localStore;
- if (account == null || store == null || _teamLockRestored == account) {
- return;
- }
- if (_teamAccountHere() == null) return;
- _teamLockRestored = account;
- List<String> tabs;
- try {
- final raw = await store.read(_teamLockKey(account));
- tabs = raw == null
- ? const []
- : [
- for (final id in jsonDecode(raw) as List)
- if (id is String) id,
- ];
- } catch (error) {
- appLog.info('super-tabs', 'team account lock not read: $error');
- return;
- }
- if (tabs.isEmpty || _disposed || currentUser?.id != account) return;
- final setup = await teamSetupStatus();
- if (_disposed || currentUser?.id != account) return;
- if (_teamLockAccount != account) {
- _teamLockAccount = account;
- _teamLockTabs.clear();
- }
- _teamLockTabs.addAll(tabs);
- if (setup?.state == 'exists') {
- await teamAccountMade();
- return;
- }
- // A Swarm that let this computer go meanwhile (removed from Machines on
- // another device, or the person's access gone) holds nothing.
- final here = _teamAccountHere();
- if (here != null) {
- for (final tabId in tabs) {
- if (await _swarmHolds(tabId, here) == false) {
- _teamLockTabs.remove(tabId);
- }
- }
- }
- if (_disposed || currentUser?.id != account) return;
- notifyListeners();
- if (_teamLockTabs.length != tabs.length) await _saveTeamLock(account);
- }
-
- /// Whether Swarm [tabId] still has computer [here] in its Machines list, not
- /// being removed: false when it does not, or when this person can no longer
- /// open it; null when it cannot be read now (offline), which keeps the lock.
- Future<bool?> _swarmHolds(String tabId, String here) async {
- try {
- final c = await superTabs.open(tabId);
- await c.refresh();
- if (c.accessRevoked) return false;
- final snapshot = c.snapshot;
- if (snapshot == null || c.error != null) return null;
- return snapshot.machines.any(
- (m) => m['machineId'] == here && m['removal'] == null,
- );
- } on SuperTabFailure catch (failure) {
- return const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)
- ? false
- : null;
- } catch (_) {
- return null;
- }
- }
-
- /// The Swarms the lock holds for, by the names they go by, read now so
- /// Remove can say which it leaves; "a Swarm" for one that cannot be read.
- Future<List<String>> readTeamSetupLockSwarmNames() async => [
- for (final id in [..._teamLockTabs])
- switch (await _swarmName(id)) {
- final String name when name.isNotEmpty => name,
- _ => 'a Swarm',
- },
- ];
-
- /// A Swarm's name, given up after [_teamLockNameWait] (offline): Remove
- /// still asks, naming it "a Swarm".
- Future<String?> _swarmName(String tabId) async {
- try {
- return await () async {
- final c = await superTabs.open(tabId);
- if (c.snapshot == null) await c.refresh();
- return c.snapshot?.name.trim();
- }().timeout(_teamLockNameWait);
- } catch (_) {
- return null;
- }
- }
-
- static const _teamLockNameWait = Duration(seconds: 5);
-
- /// This computer's Harness Team account exists: the lock ends.
- Future<void> teamAccountMade() async {
- final account = _teamLockAccount;
- if (account == null || _teamLockTabs.isEmpty) return;
- _teamLockTabs.clear();
- notifyListeners();
- await _saveTeamLock(account);
- }
-
- /// The lock's one way out, where setup can never finish here: removes this
- /// computer from each Swarm it is held for. Null when that is done;
- /// otherwise why not, and the lock stays for the Swarms not done.
- Future<String?> removeLockedMachine() async {
- final here = _teamAccountHere();
- final account = currentUser?.id;
- if (here == null || account == null || _teamLockAccount != account) {
- return null;
- }
- for (final tabId in [..._teamLockTabs]) {
- // Already gone from it, being removed, or no longer this person's to
- // open: nothing to remove, and the lock lets it go.
- final holds = await _swarmHolds(tabId, here);
- if (holds != false) {
- try {
- final c = await superTabs.open(tabId);
- final result = await c.command({
- 'type': 'machine.remove',
- 'machineId': here,
- });
- if (result == null) {
- return c.operationError ?? 'Could not do that. Try again.';
- }
- } on SuperTabFailure catch (failure) {
- return failure.message;
- } catch (error) {
- appLog.info('super-tabs', 'machine not removed for the lock: $error');
- return 'Could not reach the Swarm. Try again.';
- }
- }
- _teamLockTabs.remove(tabId);
- notifyListeners();
- await _saveTeamLock(account);
- }
- return null;
- }
-
- /// The lock's last way out, once Remove was refused (the Mac runs a
- /// project's PM, say): "Not now", recorded with the daemon so it is not
- /// offered again on its own, and the app opens. The machine row keeps its
- /// Set up button.
- Future<void> declineTeamSetupLock() async {
- await declineTeamAccount();
- final account = _teamLockAccount;
- if (account == null || _teamLockTabs.isEmpty) return;
- _teamLockTabs.clear();
- notifyListeners();
- await _saveTeamLock(account);
- }
-
- /// The start offer, once for each process of this Mac's daemon: Macs
- /// already in a Swarm meet no join or contribute moment, and one ask a
- /// launch went to whichever daemon answered first, one still starting or the
- /// version from before an update, so nobody saw the prompt (2026-10-27).
- /// The daemon decides, and remembers a cancel. One ask at a time; a daemon
- /// that could not say is asked again a few times, with a growing wait, and
- /// a reconnect to it neither restarts the count nor cuts the wait short.
- Future<void> _offerTeamAccountAtStart() async {
- if (_disposed || _teamOfferBusy) return;
- if (!_teamAccountSystem) return;
- _teamOfferBusy = true;
- try {
- final daemon = await _daemonIdentity();
- if (_disposed) return;
- // Only a confirmed process other than the last confirmed one starts
- // over. A status read that could not say (a timeout) is no evidence of
- // a restart, and counting it as one asked without end (re-check of
- // #1790); the first identity read after an unknown one is taken as the
- // same process.
- final restarted =
- daemon != null &&
- _teamOfferDaemon != null &&
- daemon != _teamOfferDaemon;
- if (!_teamOfferStarted || restarted) {
- _teamOfferRetry?.cancel();
- _teamOfferRetry = null;
- _teamOfferStarted = true;
- _teamOfferTried = 0;
- _teamOfferAnswered = false;
- }
- _teamOfferDaemon = daemon ?? _teamOfferDaemon;
- if (_teamOfferAnswered ||
- _teamOfferTried >= _teamOfferTries ||
- _teamOfferRetry != null) {
- return;
- }
- final answered = await offerTeamAccount('startup');
- // A request still out at dispose must not schedule another.
- if (_disposed) return;
- if (answered) {
- _teamOfferAnswered = true;
- return;
- }
- _teamOfferTried++;
- if (_teamOfferTried >= _teamOfferTries) return;
- _teamOfferRetry = Timer(teamOfferRetryForTest * _teamOfferTried, () {
- _teamOfferRetry = null;
- if (!_disposed) unawaited(_offerTeamAccountAtStart());
- });
- } finally {
- _teamOfferBusy = false;
- }
- }
-
- /// This computer's own machine, when the Harness Team account can be made
- /// here: never a machine shared with this account.
+ /// This computer's own machine, when it can have a Harness Team account:
+ /// never a machine shared with this account.
String? _teamAccountHere() {
if (!_teamAccountSystem) return null;
return machineStates.values
@@ -2641,56 +2276,6 @@ class AppNotifier extends ChangeNotifier {
.machineId;
}
- /// Whether this Mac can make its Harness Team account: the machine row's
- /// Set up button shows only then.
- bool get canSetUpTeamAccount => _teamAccountHere() != null;
-
- final StreamController<String> _teamSetupAsks =
- StreamController<String>.broadcast();
-
- /// Each moment the Harness Team account is wanted on this Mac, by its
- /// reason: the screen explains it, then [setUpTeamAccount] or
- /// [declineTeamAccount].
- Stream<String> get teamSetupAsks => _teamSetupAsks.stream;
-
- /// Starts the Harness Team account's setup on this Mac, the person having
- /// asked: macOS's administrator prompt follows. Answers the daemon's state
- /// (`started`, `exists`, `running`, ...), or `update` from a daemon too old
- /// to set it up from here. With [signInAgain], an account already here is
- /// signed in again for this account: the Swarm found it serving another
- /// account of this computer (#3122).
- Future<String> setUpTeamAccount({
- bool signInAgain = false,
- bool restart = false,
- }) async {
- final here = _teamAccountHere();
- if (here == null) return 'unsupported';
- try {
- final answer = await superTabMachineRequest(here, {
- 'action': 'teamSetup',
- 'reason': 'manual',
- if (signInAgain) 'signInAgain': true,
- if (restart) 'restart': true,
- });
- return answer['state']?.toString() ?? 'started';
- } on SuperTabFailure catch (failure) {
- if (failure.code == 'INVALID_REQUEST') return 'update';
- rethrow;
- }
- }
-
- /// "Not now": not offered again on its own. The machine row keeps its Set
- /// up button.
- Future<void> declineTeamAccount() async {
- final here = _teamAccountHere();
- if (here == null) return;
- try {
- await superTabMachineRequest(here, {'action': 'teamSetupDecline'});
- } catch (error) {
- appLog.debug('super-tabs', 'team account decline not saved: $error');
- }
- }
-
/// 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
@@ -2727,44 +2312,6 @@ class AppNotifier extends ChangeNotifier {
}
}
- /// 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
- /// when it cannot say: not this Mac's to set up, or a daemon too old.
- Future<({String state, String? detail})?> teamSetupStatus() async {
- final read = await teamSetupProgress();
- return read == null ? null : (state: read.state, detail: read.detail);
- }
-
- /// [teamSetupStatus], and while setup runs, [step]: the step it is on, and
- /// [elapsed]: how long it has run, when the daemon says (the setup lock's
- /// waiting step, Scholes 2026-11-04).
- Future<({String state, String? detail, String? step, Duration? elapsed})?>
- teamSetupProgress() async {
- final here = _teamAccountHere();
- if (here == null) return null;
- try {
- final answer = await superTabMachineRequest(here, {
- 'action': 'teamSetupStatus',
- });
- final state = answer['state'];
- if (state is! String) return null;
- final detail = answer['detail'];
- final step = answer['step'];
- final elapsedMs = answer['elapsedMs'];
- return (
- state: state,
- detail: detail is String ? detail : null,
- step: step is String ? step : null,
- elapsed: elapsedMs is num && elapsedMs >= 0
- ? Duration(milliseconds: elapsedMs.round())
- : null,
- );
- } catch (_) {
- return null;
- }
- }
-
final _joinAdding = <String>{};
/// The Swarms the join's add already ran or was decided for, per account on
@@ -6398,13 +5945,6 @@ class AppNotifier extends ChangeNotifier {
// the offline poll (the one thing that would have re-probed) stopped, and the tiles sat on
// "Offline" over a live terminal with nothing left to restore them. Measured 2026-09-18 21:50.
machine.localEndpoint ??= _cliEndpoint;
- // With the person here, at each start of this Mac's daemon: a Mac that
- // joined a Swarm before teammates' work went only to Team machines never
- // met the join or contribute moment.
- if (!machine.machine.isSharedMachine) {
- unawaited(_restoreTeamSetupLock());
- unawaited(_offerTeamAccountAtStart());
- }
} else {
machine.transportMode = MachineTransportMode.cloudE2ee;
}
@@ -24206,7 +23746,6 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
- _teamOfferRetry?.cancel();
_approvalRefresh?.cancel();
if (identical(CrashLog.healthError, _measurementError)) {
CrashLog.healthError = null;
@@ -24291,7 +23830,6 @@ class AppNotifier extends ChangeNotifier {
for (final request in _joinAccountRequests) {
request.complete(null);
}
- unawaited(_teamSetupAsks.close());
super.dispose();
}
}
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index 34496074e..557b33bd5 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -36,7 +36,6 @@ class HarnessLaunchIntegration {
this.projectVisibilityLocked = false,
this.initialTask,
this.engines,
- this.forcedPermissionMode,
this.swarmRole,
this.swarmSkillMode,
this.roleSuggestions,
@@ -63,8 +62,6 @@ class HarnessLaunchIntegration {
final String? initialTask;
// The only agents this destination may start, or null for any.
final List<String>? engines;
- // A destination can require a mode without changing ordinary launch preferences.
- final String? forcedPermissionMode;
String? projectVisibility;
bool projectVisibilityLocked;
diff --git a/desktop/lib/state/lead_placement.dart b/desktop/lib/state/lead_placement.dart
index b4342b62f..04a63a825 100644
--- a/desktop/lib/state/lead_placement.dart
+++ b/desktop/lib/state/lead_placement.dart
@@ -16,7 +16,6 @@ class LeadMachine {
this.own = true,
this.native = true,
this.team = false,
- this.teamEngines,
this.engineRefusals = const {},
this.owner,
});
@@ -42,18 +41,10 @@ class LeadMachine {
/// It runs in that machine's Harness Team account.
final bool team;
- /// The engines it runs in that Mac's Harness Team account, as the server
- /// decided (backend leadStart.ts leadChoices); the others run on the Mac
- /// itself. Null from a server that does not say: then [team] holds for all.
- final Set<String>? teamEngines;
-
/// Whose machine it is, for a teammate's (its menu row wears their
/// avatar); null for the person's own.
final SuperTabPerson? owner;
- /// It runs with [engine] in that Mac's Harness Team account.
- bool inTeam(String engine) => teamEngines?.contains(engine) ?? team;
-
/// The repositories the Swarm already checked out there, as
/// [leadRepositoryKey] reads them.
final Set<String> repositories;
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index b88fc94d0..5ff425582 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -1474,10 +1474,10 @@ class NewHarnessController extends ChangeNotifier {
String get _settingsEngine => _agentPreview ?? _engine;
LocalCodexProfile? get _settingsProfile =>
_settingsEngine == _engine ? _profile : null;
- String? get _forcedPermissionMode => integration?.forcedPermissionMode;
- List<PermissionMode> get _settingsModes => _forcedPermissionMode != null
- ? const []
- : permissionModesOf(_baseOf(_settingsEngine));
+ // A Product Manager the Swarm starts on another machine starts there with
+ // its owner's own permission settings (task #4215): no choice to offer.
+ List<PermissionMode> get _settingsModes =>
+ leadThroughSwarm ? const [] : permissionModesOf(_baseOf(_settingsEngine));
String get _settingsMode =>
_settingsModes.any((mode) => mode.id == _permissionFor(_settingsEngine))
? _permissionFor(_settingsEngine)
@@ -1485,7 +1485,7 @@ class NewHarnessController extends ChangeNotifier {
bool get takesTask => isCloud || takesFirstTask(_base);
bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
List<PermissionMode> get _modes =>
- _noAgentSetup || isCloud || _forcedPermissionMode != null
+ _noAgentSetup || isCloud || leadThroughSwarm
? const []
: permissionModesOf(_base);
bool get hasModes => _modes.isNotEmpty;
@@ -1506,7 +1506,7 @@ class NewHarnessController extends ChangeNotifier {
/// Settings are offered separately so browsing never inserts list rows.
List<NewHarnessOption> agentSettingsFor(String engine) {
- final modes = _forcedPermissionMode != null
+ final modes = leadThroughSwarm
? const <PermissionMode>[]
: permissionModesOf(_baseOf(engine));
final mode =
@@ -1689,11 +1689,9 @@ class NewHarnessController extends ChangeNotifier {
/// The Product Manager line: where it starts, its engine and model.
String get leadLine {
final target = leadMachine;
- final name = target == null
- ? machineLabel
- : target.inTeam(_engine)
- ? '${target.name}’s Team account'
- : target.name;
+ // Never a Team account's: the Swarm starts a PM only on its person's own
+ // computer (backend leadStart.ts leadHost, #4120).
+ final name = target?.name ?? machineLabel;
return ['Product Manager on $name', agentLabel, leadModelLabel].join(' · ');
}
@@ -4787,17 +4785,9 @@ class NewHarnessController extends ChangeNotifier {
);
}
}
- final forcedMode = _forcedPermissionMode;
- // Only Claude Code and Codex name a full mode. Other engines use their
- // existing approving launch flags through bypassPermission.
- final permissionMode = forcedMode == null
- ? (hasModes ? mode : null)
- : permissionModesOf(base).any((mode) => mode.id == forcedMode)
- ? forcedMode
- : null;
+ final permissionMode = hasModes ? mode : null;
final bypass =
- forcedMode != null ||
- (permissionMode != null && permissionModeApproves(permissionMode));
+ permissionMode != null && permissionModeApproves(permissionMode);
final folder = _project.folder;
final firstMessage = task.trim();
String launchMessage = firstMessage;
@@ -4829,10 +4819,7 @@ class NewHarnessController extends ChangeNotifier {
final launchSetup = LaunchSetup(
engine: base,
harnessId: harness,
- // A Swarm's required mode is not the person's next ordinary launch choice.
- permissionMode: _forcedPermissionMode != null
- ? _permissionFor(base)
- : permissionMode ?? kDefaultPermissionMode,
+ permissionMode: permissionMode ?? kDefaultPermissionMode,
model: model,
profile: base == 'codex' && model == null && !asGuest ? _profile : null,
profileMachineId: _machineId,
diff --git a/desktop/lib/super_tabs/add_computers.dart b/desktop/lib/super_tabs/add_computers.dart
index ef92bd6ad..ec7810249 100644
--- a/desktop/lib/super_tabs/add_computers.dart
+++ b/desktop/lib/super_tabs/add_computers.dart
@@ -40,28 +40,15 @@ class AddComputerRow {
final String? tag, reason;
}
-/// Why teammates' work does not run on a computer yet, from the Swarm's
-/// refusal code (backend superTabs/machines.ts `teamWorkRefusal`) and, for
-/// this computer, what its daemon remembers of the Team account setup: a word
-/// or two for the row, and the whole of it for its tooltip. Null when it does
-/// run there, or for a code this build does not know.
-({String tag, String reason})? _teamWhy(
- Object? code,
- ({String state, String? detail})? setup,
-) {
+/// Why teammates' work does not run on a computer's existing Team account,
+/// from the Swarm's refusal code (backend superTabs/machines.ts
+/// `teamWorkRefusal`): a word or two for the row, and the whole of it for its
+/// tooltip. Null when it does run there, or for a code this build does not
+/// know. A computer without one is not short of anything: Swarm v3 makes
+/// none (#4221).
+({String tag, String reason})? _teamWhy(Object? code) {
const only = 'so only your projects run here.';
return switch (code) {
- 'TEAM_ACCOUNT_REQUIRED' => switch (setup?.state) {
- 'failed' => (
- tag: 'setup failed',
- reason: 'Team account setup failed, $only',
- ),
- 'running' => (
- tag: 'setting up',
- reason: 'Its Team account is being set up, $only',
- ),
- _ => (tag: 'not set up', reason: 'No Team account yet, $only'),
- },
'PRIVACY_UNCHECKED' => (
tag: 'not checked',
reason: 'Its Team account hasn’t passed the privacy check yet, $only',
@@ -91,7 +78,6 @@ List<AddComputerRow> addComputerRows(
AppNotifier app,
SuperTabController c, {
Set<String> added = const {},
- ({String state, String? detail})? teamSetup,
}) {
final snapshot = c.snapshot;
final pools = snapshot?.machines ?? const <Map<String, dynamic>>[];
@@ -117,14 +103,8 @@ List<AddComputerRow> addComputerRows(
final team = pools.where((p) => p['hostMachineId'] == id).firstOrNull;
final work = (team ?? pool)?['teamWork'];
if (work is Map && work['allowed'] == false) {
- why = _teamWhy(work['code'], here ? teamSetup : null);
+ why = _teamWhy(work['code']);
}
- } else if (teamAccounts && here && teamSetup?.state == 'failed') {
- why = (
- tag: 'setup failed',
- reason:
- 'Team account setup failed, so only your projects will run here.',
- );
}
rows.add(
AddComputerRow(
@@ -216,21 +196,6 @@ class _AddComputersState extends State<_AddComputers> {
/// The computers the last Add asked for.
var _requested = <String>{};
bool _busy = false, _closing = false;
- ({String state, String? detail})? _teamSetup;
-
- @override
- void initState() {
- super.initState();
- unawaited(_readTeamSetup());
- }
-
- /// Only this computer's own daemon is asked, and only where its Team
- /// account can be made; one that cannot say leaves the Swarm's own line.
- Future<void> _readTeamSetup() async {
- if (!app.canSetUpTeamAccount) return;
- final read = await app.teamSetupStatus();
- if (mounted) setState(() => _teamSetup = read);
- }
bool get _sameAccount => app.currentUser?.id == _accountId;
@@ -238,8 +203,7 @@ class _AddComputersState extends State<_AddComputers> {
/// may still change this Swarm.
bool _alive() => mounted && !_closing && _sameAccount && c.canWrite;
- List<AddComputerRow> get _rows =>
- addComputerRows(app, c, added: _added, teamSetup: _teamSetup);
+ List<AddComputerRow> get _rows => addComputerRows(app, c, added: _added);
bool _ticked(AddComputerRow row) =>
row.status == AddComputerStatus.ready && (_ticks[row.id] ?? true);
diff --git a/desktop/lib/super_tabs/import_agent_dialog.dart b/desktop/lib/super_tabs/import_agent_dialog.dart
index 76437fd9b..0a3efdacd 100644
--- a/desktop/lib/super_tabs/import_agent_dialog.dart
+++ b/desktop/lib/super_tabs/import_agent_dialog.dart
@@ -21,7 +21,6 @@ import 'detail_dialog.dart';
import 'dialog_scope.dart';
import 'import_agent.dart';
import 'model.dart';
-import 'team_account_setup.dart';
/// Whether Add agent offers Import: Harness on a Mac or a Windows PC, where its
/// daemon and a Harness Team account are; never the web or Linux.
@@ -169,14 +168,7 @@ class _ImportAgentDialogState extends State<_ImportAgentDialog> {
return SuperTabDetailDialog(
title: title,
body: Text(why, style: DesktopChrome.control()),
- actions: [
- cancel,
- if (why == kImportNeedsTeamAccount && app.canSetUpTeamAccount)
- FilledButton(
- onPressed: () => showTeamAccountSetup(context, app),
- child: const Text('Set up Harness Team'),
- ),
- ],
+ actions: [cancel],
);
}
final handoff = _handoff;
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index 6d8cc749e..155b49a40 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -126,7 +126,6 @@ class SuperTabLaunch {
late final HarnessLaunchIntegration integration;
integration =
HarnessLaunchIntegration(
- forcedPermissionMode: 'full',
startInSwarm: leadMachines == null
? null
: (start) async {
@@ -537,12 +536,6 @@ class SuperTabLaunch {
.firstOrNull,
native: own && connected,
team: server ? shownHost != null && shownHost != id : team,
- teamEngines: server
- ? {
- for (final MapEntry(:key, :value) in decided.entries)
- if (value != id) key,
- }
- : null,
engineRefusals: engineRefusals,
unavailable: snapshot.paused
? kLeadSwarmPaused
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index c790f0be1..423d0d25e 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -47,9 +47,7 @@ import 'model.dart';
import 'join_machine.dart'
show superTabOldJoinSuggestion, superTabSuggestedAgentSlots;
import 'personal_machine_rows.dart';
-import 'team_account_setup.dart';
import 'section_heading.dart';
-import 'swarm_switcher.dart' show PersonalSwarm;
import '../widgets/laid_out_list.dart';
export 'machine_status.dart';
@@ -379,7 +377,6 @@ Future<bool> _sendContribution(
required bool memory,
required bool Function() alive,
bool teamAccountOnly = false,
- bool offerTeamAccount = true,
bool ifMissing = false,
bool unlessRemoved = false,
}) async {
@@ -420,14 +417,6 @@ Future<bool> _sendContribution(
);
}
await app.wakeSuperTabHost(machineId);
- // This Mac, added while its person is here: macOS asks once for the Harness
- // Team account (cli/src/team/autoSetup.ts). Never for the Personal Swarm,
- // which has no teammates to run work for (Diego, 2026-11-03).
- if (offerTeamAccount &&
- app.stateOf(machineId)?.isLocalMachine == true &&
- PersonalSwarm.of(app).id != c.tabId) {
- unawaited(app.offerTeamAccount('contribute', tabId: c.tabId));
- }
return true;
}
@@ -438,9 +427,7 @@ Future<bool> _sendContribution(
/// [setupId] is the caller's to keep between tries: a setup still running
/// answers the next try with the same one. With [teamAccountOnly], teammates'
/// work reaches it only through its Harness Team account once that passes its
-/// privacy check (backend superTabs/machines.ts `teamWorkRefusal`). Without
-/// [offerTeamAccount], this Mac is not offered a Harness Team account: a
-/// Personal Swarm has no teammates to run work for.
+/// privacy check (backend superTabs/machines.ts `teamWorkRefusal`).
/// [readResources] stands in for [AppNotifier.readMachineResources].
Future<String?> contributeComputer(
SuperTabController c,
@@ -449,7 +436,6 @@ Future<String?> contributeComputer(
required String setupId,
required bool Function() alive,
bool teamAccountOnly = false,
- bool offerTeamAccount = true,
bool ifMissing = false,
bool unlessRemoved = false,
Future<MachineResources?> Function(String machineId)? readResources,
@@ -484,7 +470,6 @@ Future<String?> contributeComputer(
memory: true,
alive: alive,
teamAccountOnly: teamAccountOnly,
- offerTeamAccount: offerTeamAccount,
ifMissing: ifMissing,
unlessRemoved: unlessRemoved,
);
@@ -736,10 +721,6 @@ Future<void> _machineSettingsDialog(
maxAgents: atMost ?? memoryLimit(prepared),
memory: atMost == null,
alive: () => context.mounted,
- // The machine is in the Swarm already: changing its
- // settings is no moment to ask for the Team account, and
- // asking locked the app (Diego, 2026-11-03).
- offerTeamAccount: false,
)) {
return;
}
@@ -869,35 +850,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
bool _reading = false;
int _revision = 0;
- /// What this Mac's daemon remembers of its Harness Team account setup
- /// ([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
- /// step and time left; null without the app's lock in the window.
- TeamSetupWatch? _setupWatch;
-
- void _followSetupWatch() {
- final app = widget.app;
- final watch = app == null ? null : TeamSetupWatch.of(app);
- if (identical(watch, _setupWatch)) return;
- _setupWatch?.removeListener(_setupMoved);
- _setupWatch = watch?..addListener(_setupMoved);
- }
-
- /// The row says the step as it moves, and what the daemon remembers once
- /// setup ends.
- void _setupMoved() {
- if (!mounted) return;
- _changed();
- if (_setupWatch?.running == false) unawaited(_readTeamSetup());
- }
+ bool _teamJoinReading = false;
SuperTabController get c => widget.controller;
// Team agents only: a Buddy is listed nowhere, and its machine may be its
@@ -917,8 +873,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
void initState() {
super.initState();
c.machinesChanged.addListener(_machinesMoved);
- _followSetupWatch();
- unawaited(_readTeamSetup());
+ unawaited(_readTeamJoin());
if ((!kUnderTest || widget.readLocal != null) && widget.app != null) {
_updateUsage();
widget.app!.foreground.addListener(_foreground);
@@ -1022,38 +977,32 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
view.agents.length,
]);
- /// Reads why this Mac has no Harness Team account, only while its person's
- /// own row offers Set up: asked of this Mac's daemon, never of another's.
- Future<void> _readTeamSetup() async {
+ /// Reads why this Mac's Team account has not joined, only while its
+ /// person's own row reads joining: asked of this Mac's daemon, never of
+ /// another's.
+ Future<void> _readTeamJoin() async {
final app = widget.app;
- if (app == null || _teamSetupReading || !app.canSetUpTeamAccount) return;
- bool own(String code) =>
+ if (app == null || _teamJoinReading) return;
+ final joining =
c.snapshot?.machines.any(
(m) =>
m['contributorId'] == c.accountId &&
app.stateOf(m['machineId'] as String)?.isLocalMachine == true &&
- (m['teamWork'] as Map?)?['code'] == code,
+ (m['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_JOINING',
) ==
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;
+ if (!joining) {
+ _teamJoin = null;
+ return;
+ }
+ _teamJoinReading = true;
try {
- final read = setup ? await app.teamSetupStatus() : null;
- final join = joining ? await app.teamJoinStatus() : null;
+ final join = await app.teamJoinStatus();
if (!mounted) return;
- 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.
- if (read?.state == 'running') TeamSetupWatch.of(app)?.follow();
+ _teamJoin = join;
_changed();
} finally {
- _teamSetupReading = false;
+ _teamJoinReading = false;
}
}
@@ -1113,7 +1062,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
}
_samples.removeWhere((id, _) => !_ids.contains(id));
_awaiting.removeWhere((id) => !_samples.containsKey(id));
- await _readTeamSetup();
+ await _readTeamJoin();
} finally {
_reading = false;
// A Swarm that isn't showing reads nothing; coming back reads at once ([_machinesMoved]).
@@ -1131,7 +1080,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
_timer?.cancel();
_tick?.cancel();
c.machinesChanged.removeListener(_machinesMoved);
- _setupWatch?.removeListener(_setupMoved);
for (final beat in _rowBeats.values) {
beat.dispose();
}
@@ -1408,7 +1356,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
/// Everything a machine's row, its tooltip and its details say of it, read once per build.
_MachineView _view(String id) {
- _followSetupWatch();
final app = widget.app, snapshot = c.snapshot!;
final shared = snapshot.pool(id);
// The Mac's Harness Team account is part of its row: its agents are listed here, and everyone but the Mac's owner
@@ -1584,23 +1531,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
final line = _teammatesLine(shared, team, contributor);
// Sorted once, for both the row's line and its details (task #3412).
final crew = superTabMachineCrew(agents);
- final restartTeam =
- team != null &&
- (team['teamWork'] as Map?)?['code'] == 'MACHINE_OFFLINE' &&
- contributor == c.accountId &&
- app != null &&
- app.canSetUpTeamAccount &&
- app.stateOf(id)?.isLocalMachine == true &&
- (status == SuperTabMachineStatus.live ||
- status == SuperTabMachineStatus.late);
- final setUpTeam =
- line != null &&
- team == null &&
- (shared?['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_REQUIRED' &&
- contributor == c.accountId &&
- 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 =
@@ -1609,20 +1539,11 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
(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.
- final progress = (setUpTeam || restartTeam) ? _setupWatch?.line : null;
- final problem = progress != null
- ? '$progress\nKeep working. We\'ll tell you when it\'s ready.'
- : setUpTeam
- ? superTabTeamSetupLine(_teamSetup) ?? line
- : joinLine ?? line;
+ final problem = joinLine ?? line;
return _MachineView(
apiModels: apiModels,
localModels: localModels,
@@ -1635,15 +1556,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
crew,
diskFree: dim ? null : diskFree?.toDouble(),
),
- // Set up would ask for the password again while one setup runs.
- setUpTeam:
- ((setUpTeam || restartTeam) && progress == null) || joinLine != null,
retryJoin: joinLine != null,
- setUpTeamLabel: joinLine != null
- ? 'Retry'
- : restartTeam
- ? 'Restart'
- : superTabTeamSetupAction(_teamSetup),
owner: person,
contributor: contributor,
shared: shared,
@@ -2293,27 +2206,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
onMore: BrowserMenuGuard.inBrowser
? (at) => _menu(view, at)
: null,
- onSetUpTeam: view.retryJoin
+ onRetryJoin: view.retryJoin
? () async {
await widget.app!.retryTeamJoin();
- await _readTeamSetup();
- }
- : view.setUpTeam
- ? () async {
- await showTeamAccountSetup(
- context,
- widget.app!,
- restart: view.setUpTeamLabel == 'Restart',
- missing: view.setUpTeamLabel == 'Restart'
- ? 'Harness Team account offline'
- : _teamSetup?.state == 'incomplete'
- ? _teamSetup?.detail ?? ''
- : null,
- signInAgain:
- view.setUpTeamLabel != 'Restart' &&
- _teamSetup?.state == 'exists',
- );
- await _readTeamSetup();
+ await _readTeamJoin();
}
: null,
),
@@ -3017,9 +2913,7 @@ class _MachineView {
this.history,
this.crew = const [],
this.crewLine,
- this.setUpTeam = false,
this.retryJoin = false,
- this.setUpTeamLabel = 'Set up',
this.apiModels = const [],
this.localModels = const [],
this.access = const [],
@@ -3030,15 +2924,9 @@ class _MachineView {
final String id, name, details, tip;
- /// 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.
+ /// The row's button retries this Mac's join of its Team account (#3215), its own person looking.
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;
-
/// Its one line when teammates' agents cannot run there ([superTabTeammatesPaused]); null otherwise.
final String? problem;
@@ -3123,28 +3011,6 @@ String? superTabTeammatesPaused(Object? code) {
return why == null ? null : "Teammates' agents paused: $why";
}
-/// This Mac's own row, for its person, when its daemon remembers why it has no Harness Team account
-/// (cli/src/team/autoSetup.ts `status`); null when it does not, and the Swarm's own line stands.
-String? superTabTeamSetupLine(({String state, String? detail})? setup) {
- final detail = setup?.detail?.trim().replaceFirst(RegExp(r'[.]+$'), '');
- final why = switch (setup?.state) {
- 'declined' => 'setup was cancelled',
- 'failed' when detail != null && detail.isNotEmpty =>
- 'setup failed: $detail',
- 'failed' => 'setup failed',
- 'running' => 'setting up',
- // The account is there, a part of it is not (cli/src/team/autoSetup.ts `missingDetail`, #2765).
- 'incomplete' when detail != null && detail.isNotEmpty =>
- 'Harness Team is not finished ($detail)',
- 'incomplete' => 'Harness Team is not finished',
- // The Swarm has no Team account for this row while this Mac has one: it serves another account of this computer,
- // the one signed in here before (#3122).
- 'exists' => 'Harness Team on this computer works for another account',
- _ => null,
- };
- 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) {
@@ -3159,13 +3025,6 @@ String? superTabTeamJoinLine(({String? failure, bool hostRunning}) join) {
: "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) =>
- setup?.state == 'incomplete' || setup?.state == 'exists'
- ? 'Repair'
- : 'Set up';
-
/// Who had this computer's row before the account signed in on it now, and until when: "Was kelvin until 5 Nov"
/// (backend machines.ts previousOwner, #3122). Null for a row never moved, or one whose person is not in the Swarm.
String? superTabMachineHistory(
@@ -3359,7 +3218,7 @@ class _MachineProjectsSettingState extends State<_MachineProjectsSetting> {
class _MachineLine extends StatelessWidget {
const _MachineLine({
required this.view,
- this.onSetUpTeam,
+ this.onRetryJoin,
this.onMore,
this.words = false,
});
@@ -3372,8 +3231,8 @@ class _MachineLine extends StatelessWidget {
/// In a browser, opens the machine's menu at a point until it closes: the ⋯ that needs no right-click.
final Future<void> Function(Offset at)? onMore;
- /// This Mac's row, without its Harness Team account: Set up under the paused line.
- final VoidCallback? onSetUpTeam;
+ /// This Mac's row, its Team account not joined: Retry under the paused line.
+ final VoidCallback? onRetryJoin;
@override
Widget build(BuildContext context) {
@@ -3468,17 +3327,17 @@ class _MachineLine extends StatelessWidget {
style: DesktopChrome.metadata(),
),
// The design system's secondary action, as themed (desktop-design-system.md): no local style.
- if (problem != null && onSetUpTeam != null)
+ if (problem != null && onRetryJoin != null)
Padding(
padding: const EdgeInsets.only(
top: grid.AppDesktop.controlGap,
),
child: OutlinedButton(
key: ValueKey(
- 'super-machine-team-setup-${view.id}',
+ 'super-machine-team-retry-${view.id}',
),
- onPressed: onSetUpTeam,
- child: Text(view.setUpTeamLabel),
+ onPressed: onRetryJoin,
+ child: const Text('Retry'),
),
),
],
diff --git a/desktop/lib/super_tabs/personal_lead.dart b/desktop/lib/super_tabs/personal_lead.dart
index 5466650ce..7568504f4 100644
--- a/desktop/lib/super_tabs/personal_lead.dart
+++ b/desktop/lib/super_tabs/personal_lead.dart
@@ -306,7 +306,9 @@ class PersonalLeadStarter extends ChangeNotifier {
)
: null,
swarmId: tab.id,
- permissionMode: integration.forcedPermissionMode,
+ // No dialog, so no mode the person chose: the PM starts with its owner's
+ // own permission settings (Swarm v3, task #4215).
+ bypassPermission: false,
swarmRole: integration.swarmRole,
swarmSkillMode: integration.swarmSkillMode,
prompt: prompt,
diff --git a/desktop/lib/super_tabs/personal_machines.dart b/desktop/lib/super_tabs/personal_machines.dart
index 6494c8c5d..f34da91a2 100644
--- a/desktop/lib/super_tabs/personal_machines.dart
+++ b/desktop/lib/super_tabs/personal_machines.dart
@@ -236,7 +236,6 @@ class PersonalMachines extends ChangeNotifier {
// decides, whatever this computer's read was.
ifMissing: true,
unlessRemoved: true,
- offerTeamAccount: false,
);
if (added == null) return;
_failures.remove(key);
diff --git a/desktop/lib/super_tabs/swarm_switcher.dart b/desktop/lib/super_tabs/swarm_switcher.dart
index f22f96393..7050d977b 100644
--- a/desktop/lib/super_tabs/swarm_switcher.dart
+++ b/desktop/lib/super_tabs/swarm_switcher.dart
@@ -291,7 +291,6 @@ class PersonalSwarm extends ChangeNotifier {
// As Add machine: where the Swarm runs teammates' work through Team
// accounts, this Mac is never lent under its owner's own login.
teamAccountOnly: snapshot.teamAccounts,
- offerTeamAccount: false,
// The server decides, whatever this computer read.
ifMissing: true,
unlessRemoved: true,
diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dart
deleted file mode 100644
index 5fa916e7a..000000000
--- a/desktop/lib/super_tabs/team_account_setup.dart
+++ /dev/null
@@ -1,1077 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-
-import '../core/runtime_platform.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
-import '../state/app_state.dart';
-import 'controller.dart';
-
-/// The Harness Team account explained before the system asks for the password (cli/src/team/autoSetup.ts). macOS's
-/// own prompt is titled "osascript" with a script icon, and on 2026-10-27 people met it with no idea it was Harness's.
-///
-/// [asked]: Harness offered it (a join, this computer added to a Swarm, or the app opening); "Not now" is then
-/// remembered so it is not offered again on its own. Otherwise the person pressed Set up on this computer's row, and
-/// Cancel forgets nothing.
-///
-/// [operatingSystem]: whose words, by [RuntimePlatform.operatingSystem] (this computer's when null).
-Future<void> showTeamAccountSetup(
- BuildContext context,
- AppNotifier app, {
- bool asked = false,
- String? operatingSystem,
- String? missing,
- bool signInAgain = false,
- bool restart = false,
-}) => showAppDialog<void>(
- context: context,
- barrierDismissible: false,
- builder: (context) => _TeamAccountSetup(
- app: app,
- asked: asked,
- missing: signInAgain ? 'it is signed in for another account' : missing,
- signInAgain: signInAgain,
- restart: restart,
- words: _Words.of(operatingSystem ?? RuntimePlatform.operatingSystem),
- ),
-);
-
-/// What the dialog says on one system. A Mac's prompt is macOS's "osascript" window; Linux asks through the system's
-/// own password prompt (pkexec, or sudo in a terminal), Windows through User Account Control.
-class _Words {
- const _Words({
- required this.title,
- required this.account,
- required this.prompt,
- required this.started,
- required this.exists,
- required this.update,
- required this.cannot,
- required this.unreachable,
- required this.lead,
- required this.waiting,
- required this.rejected,
- required this.cancelled,
- required this.removeWhy,
- required this.removeOnly,
- required this.remove,
- required this.here,
- this.noPrompt,
- });
-
- factory _Words.of(String operatingSystem) => switch (operatingSystem) {
- 'linux' => const _Words(
- title: 'Set up Harness Team on this computer',
- account: _computerAccount,
- prompt: 'Your system asks for your password once.',
- started:
- 'Your system is asking for your password. After that, setup goes on '
- 'in the background: this computer\'s row in Machines shows how far it is, '
- 'and Harness tells you when it is ready.',
- exists: _computerExists,
- update: _computerUpdate,
- cannot: _computerCannot,
- unreachable: _computerUnreachable,
- noPrompt: 'Run harness team setup in a terminal on this computer.',
- lead: _computerLead,
- waiting:
- 'Your system is asking for your password. After that, setup goes on '
- 'in the background and you can keep working.',
- rejected: 'Your system did not accept that password. Try again.',
- cancelled: 'The password window was closed before setup finished.',
- removeWhy:
- 'No administrator password for this computer? Remove it from the Swarm. '
- 'You can add it again from Machines.',
- removeOnly: _computerRemoveOnly,
- remove: _computerRemove,
- here: 'this computer',
- ),
- 'windows' => const _Words(
- title: 'Set up Harness Team on this computer',
- account: _computerAccount,
- prompt: 'Windows asks for permission once (User Account Control).',
- started:
- 'Windows is asking for permission. After that, setup goes on '
- 'in the background: this computer\'s row in Machines shows how far it is, '
- 'and Harness tells you when it is ready.',
- exists: _computerExists,
- update: _computerUpdate,
- cannot: _computerCannot,
- unreachable: _computerUnreachable,
- lead: _computerLead,
- waiting:
- 'Windows is asking for permission. After that, setup goes on '
- 'in the background and you can keep working.',
- rejected: 'Windows did not give permission. Try again.',
- cancelled: 'The permission window was closed before setup finished.',
- removeWhy:
- 'No administrator permission on this computer? Remove it from the Swarm. '
- 'You can add it again from Machines.',
- removeOnly: _computerRemoveOnly,
- remove: _computerRemove,
- here: 'this computer',
- ),
- _ => const _Words(
- title: 'Set up Harness Team on this Mac',
- account:
- 'Teammates\' agents in your Swarms run on this Mac in a separate macOS '
- 'account, Harness Team. They cannot read your files or use your GitHub login. '
- 'They use this Mac\'s Claude Code and Codex subscriptions, so nobody signs in again.',
- prompt:
- 'macOS asks for your password once, in a window titled “osascript”. '
- 'That is the macOS tool Harness uses to ask.',
- started:
- 'macOS is asking for your password in a window titled “osascript”. '
- 'After that, setup goes on in the background: this Mac\'s row in '
- 'Machines shows how far it is, and Harness tells you when it is ready.',
- exists: 'Harness Team is already set up on this Mac.',
- update:
- 'This Mac\'s Harness is too old to set it up from here. Update Harness, '
- 'or run harness team setup in Terminal.',
- cannot: 'Harness Team cannot be set up on this Mac right now.',
- unreachable: 'Could not reach Harness on this Mac. Try again.',
- lead:
- 'This Mac joined a Swarm, so it needs Harness Team before you go on.',
- waiting:
- 'macOS is asking for your password in a window titled “osascript”. '
- 'After that, setup goes on in the background and you can keep working.',
- rejected: 'macOS did not accept that password. Try again.',
- cancelled: 'The password window was closed before setup finished.',
- removeWhy:
- 'No administrator password for this Mac? Remove it from the Swarm. '
- 'You can add it again from Machines.',
- removeOnly: 'To go on, remove this Mac from the Swarm. You can add it again from Machines.',
- remove: 'Remove this Mac from the Swarm',
- here: 'this Mac',
- ),
- };
-
- static const _computerLead =
- 'This computer joined a Swarm, so it needs Harness Team before you go on.';
-
- /// The dialog's title when it repairs (#2765): "Repair Harness Team on this Mac".
- String get repairTitle => title.replaceFirst('Set up', 'Repair');
-
- /// What it says first when it repairs: what is missing, and that Repair runs the setup again.
- String unfinished(String missing) => missing.isEmpty
- ? 'Harness Team is not finished on $here. Repair runs its setup again.'
- : 'Harness Team is not finished on $here: $missing. Repair runs its setup again.';
-
- /// Once Remove was refused: Not now is the way on, and it says so instead
- /// of asking for Remove again.
- String get notNowWhy =>
- 'Choose Not now to go on without it. You can set up Harness Team on '
- '$here later from Machines.';
-
- static const _computerRemoveOnly =
- 'To go on, remove this computer from the Swarm. You can add it again from Machines.';
- static const _computerRemove = 'Remove this computer from the Swarm';
-
- static const _computerAccount =
- 'Teammates\' agents in your Swarms run on this computer in a separate '
- 'account, Harness Team. They cannot read your files or use your GitHub login. '
- 'They use this computer\'s Claude Code and Codex subscriptions, so nobody signs in again.';
- static const _computerExists =
- 'Harness Team is already set up on this computer.';
- static const _computerUpdate =
- 'This computer\'s Harness is too old to set it up from here. Update Harness, '
- 'or run harness team setup in a terminal.';
- static const _computerCannot =
- 'Harness Team cannot be set up on this computer right now.';
- static const _computerUnreachable =
- 'Could not reach Harness on this computer. Try again.';
-
- final String title,
- account,
- prompt,
- started,
- exists,
- update,
- cannot,
- unreachable;
-
- /// The lock's ([TeamAccountSetupLock]): why the app waits, setup under way,
- /// the password refused, the system's window closed, and the one way out.
- final String lead,
- waiting,
- rejected,
- cancelled,
- removeWhy,
- removeOnly,
- remove;
-
- /// "this Mac", or "this computer": what Remove takes out of the Swarms.
- final String here;
-
- /// The line under the password wait: how long it has waited.
- static String sofar(Duration elapsed) {
- final seconds = elapsed.inSeconds;
- final time = seconds < 60
- ? '$seconds s'
- : '${seconds ~/ 60} min ${seconds % 60} s';
- return '$time so far.';
- }
-
- /// [cancelled] for a notice, which says first that setup did not finish:
- /// "The password window was closed."
- String get closed => cancelled.replaceFirst(' before setup finished', '');
-
- /// What Remove asks before it removes anything (security review of #2779):
- /// it deletes this computer from each Swarm in [swarms], which it names.
- String confirmRemove(List<String> swarms) {
- final names = switch (swarms.length) {
- 0 => 'the Swarm',
- 1 => swarms.single,
- _ =>
- '${swarms.sublist(0, swarms.length - 1).join(', ')} and ${swarms.last}',
- };
- return 'Remove $here from $names? Its agents there stop, and teammates\' '
- 'work no longer runs on it. You can add it again from Machines.';
- }
-
- /// For the daemon's `no-prompt` (cli/src/team/autoSetup.ts): no desktop session to ask in, so the terminal is the
- /// way. Null where that never happens.
- final String? noPrompt;
-}
-
-class _TeamAccountSetup extends StatefulWidget {
- const _TeamAccountSetup({
- required this.app,
- required this.asked,
- required this.words,
- this.missing,
- this.signInAgain = false,
- this.restart = false,
- });
-
- final AppNotifier app;
- final bool asked;
- final _Words words;
-
- /// The account is there, signed in for another account of this computer (#3122): Repair signs it in for this one.
- final bool signInAgain;
- final bool restart;
-
- /// The account is there and these parts are not (cli/src/team/autoSetup.ts `missingDetail`, #2765): the dialog
- /// repairs instead of setting up. Empty for a part it could not name.
- final String? missing;
-
- @override
- State<_TeamAccountSetup> createState() => _TeamAccountSetupState();
-}
-
-class _TeamAccountSetupState extends State<_TeamAccountSetup> {
- bool _busy = false;
-
- /// What happened once the person pressed Continue; null before.
- String? _outcome;
-
- Future<void> _continue() async {
- setState(() => _busy = true);
- final words = widget.words;
- String outcome;
- try {
- final state = await widget.app.setUpTeamAccount(
- signInAgain: widget.signInAgain,
- restart: widget.restart,
- );
- // The row and the notice follow it from here (#3169): the dialog's OK
- // leaves the person free while it runs.
- if (state == 'started' || state == 'running') {
- TeamSetupWatch.of(widget.app)?.follow(restart: state == 'started');
- }
- outcome = switch (state) {
- 'started' || 'running' => words.started,
- 'exists' => words.exists,
- 'update' => words.update,
- // The daemon's answer when no prompt can be shown here (Linux with no
- // desktop session in its environment): nothing ran.
- 'no-prompt' when words.noPrompt != null => words.noPrompt!,
- _ => words.cannot,
- };
- } on SuperTabFailure catch (failure) {
- outcome = failure.code == 'NO_PROMPT'
- ? words.noPrompt ?? failure.message
- : failure.message;
- } catch (_) {
- outcome = words.unreachable;
- }
- if (mounted) {
- setState(() {
- _busy = false;
- _outcome = outcome;
- });
- }
- }
-
- Future<void> _notNow() async {
- if (widget.asked) await widget.app.declineTeamAccount();
- if (mounted) Navigator.pop(context);
- }
-
- @override
- Widget build(BuildContext context) {
- final body = grid.AppType.body(height: 1.45);
- final muted = body.copyWith(color: Theme.of(context).hintColor);
- final outcome = _outcome;
- final words = widget.words;
- final missing = widget.missing;
- return AlertDialog(
- key: const Key('team-account-setup'),
- title: Text(missing == null ? words.title : words.repairTitle),
- content: SizedBox(
- width: 420,
- child: outcome != null
- ? Text(
- outcome,
- key: const Key('team-account-setup-outcome'),
- style: body,
- )
- : Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- missing == null ? words.account : words.unfinished(missing),
- style: body,
- ),
- const SizedBox(height: 12),
- Text(words.prompt, style: body),
- const SizedBox(height: 12),
- Text(
- 'Your home folder becomes private to you. Your own agents work as before. '
- 'To remove the account later, run harness team remove.',
- style: muted,
- ),
- ],
- ),
- ),
- actions: outcome != null
- ? [
- FilledButton(
- key: const Key('team-account-setup-done'),
- onPressed: () => Navigator.pop(context),
- child: const Text('OK'),
- ),
- ]
- : [
- TextButton(
- key: const Key('team-account-setup-later'),
- onPressed: _busy ? null : _notNow,
- child: Text(widget.asked ? 'Not now' : 'Cancel'),
- ),
- FilledButton(
- key: const Key('team-account-setup-continue'),
- onPressed: _busy ? null : _continue,
- child: Text(missing == null ? 'Continue' : 'Repair'),
- ),
- ],
- );
- }
-}
-
-/// Holds the whole app while this computer's Harness Team account must be set
-/// up ([AppNotifier.teamSetupLocked]): from the moment it joins a Swarm, or is
-/// added to one, until setup succeeds (Scholes, 2026-11-03). It sits above the
-/// Navigator (app_shell.dart), so every route, dialog and menu is under it,
-/// and nothing there takes a click, a key, focus or a screen reader. There is
-/// no close. Where setup can never finish here (no administrator password, a
-/// Harness too old, a system that cannot ask), the one way out is removing
-/// this computer from the Swarm.
-///
-/// The password is asked only by the system's own prompt, through the same
-/// daemon actions as Set up on the machine row.
-///
-/// Nothing in it may need an Overlay (no tooltips): there is none above the
-/// Navigator.
-class TeamAccountSetupLock extends StatefulWidget {
- const TeamAccountSetupLock({
- super.key,
- required this.app,
- required this.child,
- this.operatingSystem,
- });
-
- final AppNotifier app;
- final Widget child;
-
- /// Whose words, by [RuntimePlatform.operatingSystem] (this computer's when
- /// null).
- final String? operatingSystem;
-
- @override
- State<TeamAccountSetupLock> createState() => _TeamAccountSetupLockState();
-}
-
-enum _LockStep { intro, waiting, retry, cancelled, cannot }
-
-/// How long the system's prompt may stay open (cli/src/team/admin.ts, 15
-/// minutes), with a minute for the setup after it.
-const _setupLimit = Duration(minutes: 16);
-const _setupRead = Duration(seconds: 2);
-
-/// macOS's "The administrator user name or password was incorrect. (-60005)",
-/// as the daemon hands it back inside its detail.
-final _refusedPassword = RegExp(
- r'-60005|incorrect|not accepted|wrong password',
- caseSensitive: false,
-);
-
-String _sentence(String text) =>
- RegExp(r'[.!?]$').hasMatch(text) ? text : '$text.';
-
-/// The four steps a person reads (#3169 mockup: "step 2 of 4"), from the
-/// steps setup says (cli/src/team/script.ts `step`, ./command.ts `progress`):
-/// the account, Harness and its engines, starting it, its privacy check. Null
-/// for the password, and for a step this app does not know.
-int? teamSetupPhase(String? step) => switch (step) {
- 'account' || 'home' || 'privacy' => 1,
- 'runtime' || 'copy-engines' || 'engines' => 2,
- 'sign-in' || 'daemon' => 3,
- 'report' => 4,
- _ => null,
-};
-
-/// What each step usually takes, from this Mac's real setup of 2026-11-04
-/// (#3169): the account, homes and privacy about 8 s, Harness 3 s, the npm
-/// download of Claude Code and Codex 4 min 18 s (`engines`), the start and
-/// its check about 5 s. `copy-engines`, which took over from the download
-/// where the Mac has both, took 1.4 to 9.9 s.
-const _stepTimes = <String, Duration>{
- 'account': Duration(seconds: 4),
- 'home': Duration(seconds: 2),
- 'privacy': Duration(seconds: 2),
- 'runtime': Duration(seconds: 5),
- 'copy-engines': Duration(seconds: 10),
- 'engines': Duration(seconds: 240),
- 'sign-in': Duration(seconds: 2),
- 'daemon': Duration(seconds: 3),
- 'report': Duration(seconds: 5),
-};
-
-/// How long setup has left, at [step] after [inStep] on it; null for a step
-/// this app does not know. A step past its usual time keeps a quarter of it
-/// (at least 10 s), so a slow download never reads as done. The download is
-/// counted only once it runs: a Mac that copies its engines never has one.
-Duration? teamSetupLeft(String? step, Duration inStep) {
- final usual = _stepTimes[step];
- if (usual == null) return null;
- final floor = usual ~/ 4 > const Duration(seconds: 10)
- ? usual ~/ 4
- : const Duration(seconds: 10);
- var left = usual - inStep < floor ? floor : usual - inStep;
- final steps = _stepTimes.keys.toList();
- for (final later in steps.skip(steps.indexOf(step!) + 1)) {
- if (later != 'engines') left += _stepTimes[later]!;
- }
- return left;
-}
-
-/// This Mac's row while setup runs (#3169): "Harness Team: setting up · step
-/// 2 of 4 · about 4 min left".
-String teamSetupLine(String? step, Duration inStep) {
- final phase = teamSetupPhase(step);
- final left = teamSetupLeft(step, inStep);
- if (phase == null || left == null) return 'Harness Team: setting up';
- final time = left < const Duration(minutes: 1)
- ? 'less than a minute left'
- : 'about ${(left.inSeconds / 60).round()} min left';
- return 'Harness Team: setting up · step $phase of 4 · $time';
-}
-
-/// How a setup [TeamSetupWatch] followed ended.
-enum TeamSetupEndKind { ready, failed, cancelled }
-
-class TeamSetupEnd {
- const TeamSetupEnd(this.kind, {this.lock = '', this.notice = ''});
-
- final TeamSetupEndKind kind;
-
- /// What the lock says when it holds the app ([TeamAccountSetupLock]).
- final String lock;
-
- /// What the notice says otherwise.
- final String notice;
-}
-
-/// This computer's Harness Team setup, followed while it runs (#3169): one
-/// per app, made and ended by [TeamAccountSetupLock], which sits above every
-/// route for the app's whole life. It reads the daemon's status every 2 s,
-/// only while setup runs, and ends with [ended]: ready (the lock is let go),
-/// failed or cancelled, with words for the lock and for a notice. The machine
-/// row draws [line].
-class TeamSetupWatch extends ChangeNotifier {
- TeamSetupWatch._(this.app, this._words, this._now);
-
- static final _watches = Expando<TeamSetupWatch>('team setup watch');
-
- /// [app]'s watch, while its lock is in the window; null otherwise.
- static TeamSetupWatch? of(AppNotifier app) => _watches[app];
-
- final AppNotifier app;
- final _Words _words;
- final DateTime Function() _now;
- final _ended = StreamController<TeamSetupEnd>.broadcast();
- Timer? _read;
- int _generation = 0;
- bool _disposed = false;
- DateTime? _since, _stepSince;
-
- /// Each end of a setup it followed.
- Stream<TeamSetupEnd> get ended => _ended.stream;
-
- bool running = false;
-
- /// The step setup said last, and how long it has run.
- String? step;
- Duration? elapsed;
-
- /// Setup is past the password: the person may go on working.
- bool get afterPassword => running && step != null && step != 'password';
-
- /// The row's line while it runs after the password; null otherwise.
- String? get line {
- final since = _stepSince;
- if (!afterPassword || since == null) return null;
- return teamSetupLine(step, _now().difference(since));
- }
-
- /// Follows a setup started here or found running. One already followed is
- /// left as it is, unless [restart]: a setup just started again.
- void follow({bool restart = false}) {
- if (_disposed || (running && !restart)) return;
- _generation++;
- running = true;
- step = null;
- elapsed = Duration.zero;
- _since = _stepSince = _now();
- notifyListeners();
- _schedule();
- }
-
- void _schedule() {
- _read?.cancel();
- final generation = _generation;
- _read = Timer(_setupRead, () => unawaited(_readNow(generation)));
- }
-
- Future<void> _readNow(int generation) async {
- _read = null;
- final setup = await app.teamSetupProgress();
- if (_disposed || !running || generation != _generation) return;
- final words = _words;
- final detail = setup?.detail?.trim();
- switch (setup?.state) {
- case 'exists':
- return _end(const TeamSetupEnd(TeamSetupEndKind.ready));
- case 'failed' when detail != null && _refusedPassword.hasMatch(detail):
- return _end(
- TeamSetupEnd(
- TeamSetupEndKind.failed,
- lock: words.rejected,
- notice: _failed(words.rejected.replaceFirst(' Try again.', '')),
- ),
- );
- case 'failed':
- final said = detail == null || detail.isEmpty
- ? null
- : _sentence(detail);
- return _end(
- TeamSetupEnd(
- TeamSetupEndKind.failed,
- lock: said == null
- ? 'Setup did not finish. Try again.'
- : 'Setup did not finish: $said',
- notice: _failed(said),
- ),
- );
- case 'declined':
- return _end(
- TeamSetupEnd(
- TeamSetupEndKind.cancelled,
- lock: words.cancelled,
- notice: _failed(words.closed),
- ),
- );
- // It ended with the account there and a part not (#2765): said, and Try again repairs it.
- case 'incomplete':
- final missing = detail == null || detail.isEmpty
- ? null
- : _sentence(detail);
- return _end(
- TeamSetupEnd(
- TeamSetupEndKind.failed,
- lock: missing == null
- ? 'Setup ended, but Harness Team is not finished. Try again.'
- : 'Setup ended, but Harness Team is not finished: $missing Try again.',
- notice: missing == null
- ? 'Harness Team setup ended, but it is not finished.'
- : 'Harness Team setup ended, but it is not finished: $missing',
- ),
- );
- case 'running':
- final next = setup?.step;
- if (next != step) _stepSince = _now();
- step = next;
- final since = _since;
- elapsed =
- setup?.elapsed ?? (since == null ? null : _now().difference(since));
- notifyListeners();
- case null:
- // No answer (the daemon restarting): read again, until the limit.
- break;
- default:
- // Anything else once it stopped running ('none': it ended with no
- // account and nothing remembered, or the daemon restarted): the
- // wait is over, and it says so (Scholes, 2026-11-04).
- return _end(
- TeamSetupEnd(
- TeamSetupEndKind.failed,
- lock: 'Setup stopped before the Harness Team account was made. Try again.',
- notice: _failed('It stopped before the account was made.'),
- ),
- );
- }
- final since = _since;
- if (since != null && _now().difference(since) > _setupLimit) {
- return _end(
- TeamSetupEnd(
- TeamSetupEndKind.failed,
- lock: 'Setup did not finish. Try again.',
- notice: _failed('It ran out of time.'),
- ),
- );
- }
- _schedule();
- }
-
- static String _failed(String? why) => why == null
- ? 'Harness Team setup did not finish.'
- : 'Harness Team setup did not finish. $why';
-
- Future<void> _end(TeamSetupEnd end) async {
- _read?.cancel();
- _read = null;
- running = false;
- step = null;
- elapsed = null;
- notifyListeners();
- // Ready lets the lock go before anyone hears of it, so a notice never
- // sits under a lock that is about to end.
- if (end.kind == TeamSetupEndKind.ready) await app.teamAccountMade();
- if (!_disposed) _ended.add(end);
- }
-
- @override
- void dispose() {
- _disposed = true;
- _read?.cancel();
- unawaited(_ended.close());
- if (identical(_watches[app], this)) _watches[app] = null;
- super.dispose();
- }
-}
-
-class _TeamAccountSetupLockState extends State<TeamAccountSetupLock> {
- late final _Words _words = _Words.of(
- widget.operatingSystem ?? RuntimePlatform.operatingSystem,
- );
- _LockStep _step = _LockStep.intro;
- String? _outcome, _removeError;
- bool _busy = false;
-
- /// Remove was pressed: the panel asks before anything is removed, naming
- /// these Swarms.
- bool _confirming = false;
- List<String> _confirmSwarms = const [];
-
- late TeamSetupWatch _watch;
- StreamSubscription<TeamSetupEnd>? _ends;
-
- @override
- void initState() {
- super.initState();
- widget.app.addListener(_changed);
- _makeWatch();
- }
-
- void _makeWatch() {
- _watch = TeamSetupWatch._(widget.app, _words, DateTime.now)
- ..addListener(_changed);
- TeamSetupWatch._watches[widget.app] = _watch;
- _ends = _watch.ended.listen(_setupEnded);
- }
-
- void _dropWatch() {
- unawaited(_ends?.cancel());
- _watch
- ..removeListener(_changed)
- ..dispose();
- }
-
- @override
- void didUpdateWidget(TeamAccountSetupLock old) {
- super.didUpdateWidget(old);
- if (!identical(old.app, widget.app)) {
- old.app.removeListener(_changed);
- widget.app.addListener(_changed);
- _dropWatch();
- _makeWatch();
- }
- }
-
- @override
- void dispose() {
- widget.app.removeListener(_changed);
- _dropWatch();
- super.dispose();
- }
-
- void _changed() {
- if (!mounted) return;
- setState(() {
- if (!widget.app.teamSetupLocked) _reset();
- });
- }
-
- void _reset() {
- _step = _LockStep.intro;
- _outcome = _removeError = null;
- _busy = false;
- _confirming = false;
- }
-
- void _show(_LockStep step, String outcome) {
- if (!mounted) return;
- setState(() {
- _busy = false;
- _step = step;
- _outcome = outcome;
- });
- }
-
- /// A setup the watch followed ended. Where the lock holds the app, it says
- /// why on the lock again, with Try again; otherwise a notice says it, with
- /// Retry on a failure (#3169).
- void _setupEnded(TeamSetupEnd end) {
- if (!mounted) return;
- if (end.kind != TeamSetupEndKind.ready && widget.app.teamSetupLocked) {
- _show(
- end.kind == TeamSetupEndKind.cancelled
- ? _LockStep.cancelled
- : _LockStep.retry,
- end.lock,
- );
- return;
- }
- final messenger = ScaffoldMessenger.maybeOf(context);
- if (messenger == null) return;
- final here = _words.here.replaceFirst('this ', '');
- final ready = end.kind == TeamSetupEndKind.ready;
- messenger.showSnackBar(
- SnackBar(
- key: const Key('team-setup-notice'),
- duration: Duration(seconds: ready ? 8 : 20),
- showCloseIcon: true,
- content: Text(
- ready
- ? 'Harness Team is ready on this $here. Teammates\' agents can run here now.'
- : end.notice,
- ),
- action: ready
- ? null
- : SnackBarAction(
- key: const Key('team-setup-notice-retry'),
- label: 'Retry',
- onPressed: () => unawaited(_retry()),
- ),
- ),
- );
- }
-
- /// The notice's Retry: the system's prompt again, followed as before.
- Future<void> _retry() async {
- try {
- final state = await widget.app.setUpTeamAccount();
- if (state == 'started' || state == 'running') {
- _watch.follow(restart: state == 'started');
- }
- } catch (_) {
- if (!mounted) return;
- ScaffoldMessenger.maybeOf(context)
- ?.showSnackBar(SnackBar(content: Text(_words.unreachable)));
- }
- }
-
- Future<void> _start() async {
- setState(() {
- _busy = true;
- _removeError = null;
- });
- final words = _words;
- try {
- switch (await widget.app.setUpTeamAccount()) {
- case 'started' || 'running':
- _show(_LockStep.waiting, words.waiting);
- _watch.follow(restart: true);
- case 'exists':
- await widget.app.teamAccountMade();
- case 'update':
- _show(_LockStep.cannot, words.update);
- case 'no-prompt' when words.noPrompt != null:
- _show(_LockStep.cannot, words.noPrompt!);
- case _:
- _show(_LockStep.cannot, words.cannot);
- }
- } on SuperTabFailure catch (failure) {
- if (failure.code == 'NO_PROMPT') {
- _show(_LockStep.cannot, words.noPrompt ?? failure.message);
- } else {
- _show(_LockStep.retry, failure.message);
- }
- } catch (_) {
- _show(_LockStep.retry, words.unreachable);
- }
- }
-
- /// Try again while it waits: reads the status first, and starts setup
- /// again only when none is running.
- Future<void> _tryAgainWaiting() async {
- setState(() {
- _busy = true;
- _removeError = null;
- });
- final setup = await widget.app.teamSetupProgress();
- if (!mounted || _step != _LockStep.waiting) return;
- switch (setup?.state) {
- case 'running':
- setState(() => _busy = false);
- case 'exists':
- await widget.app.teamAccountMade();
- if (mounted) setState(() => _busy = false);
- default:
- await _start();
- }
- }
-
- Future<void> _askRemove() async {
- setState(() {
- _busy = true;
- _removeError = null;
- });
- final swarms = await widget.app.readTeamSetupLockSwarmNames();
- if (!mounted) return;
- setState(() {
- _busy = false;
- _confirming = true;
- _confirmSwarms = swarms;
- });
- }
-
- Future<void> _remove() async {
- setState(() {
- _busy = true;
- _removeError = null;
- });
- final why = await widget.app.removeLockedMachine();
- if (!mounted) return;
- setState(() {
- _busy = false;
- _confirming = false;
- _removeError = why;
- });
- }
-
- Future<void> _notNow() async {
- setState(() => _busy = true);
- await widget.app.declineTeamSetupLock();
- if (mounted) setState(() => _busy = false);
- }
-
- @override
- Widget build(BuildContext context) {
- // Past the password, setup goes on behind the person's work (#3169): the
- // lock still holds, and comes back if setup fails.
- final locked = widget.app.teamSetupLocked && !_watch.afterPassword;
- // One tree shape locked or not, so the app below is never remounted.
- return Stack(
- fit: StackFit.expand,
- children: [
- // The barrier takes every click and hides the app from a screen
- // reader; keys follow focus, which nothing under it may hold.
- ExcludeFocus(excluding: locked, child: widget.child),
- if (locked) ...[
- ModalBarrier(dismissible: false, color: dialogVeilTintOf(context)),
- _panel(context),
- ],
- ],
- );
- }
-
- Widget _panel(BuildContext context) {
- final words = _words;
- final body = grid.AppType.body(height: 1.45);
- final muted = body.copyWith(color: Theme.of(context).hintColor);
- final outcome = _outcome;
- final retry = FilledButton(
- key: const Key('team-account-lock-retry'),
- autofocus: true,
- onPressed: _busy ? null : _start,
- child: const Text('Try again'),
- );
- // It deletes this computer from the Swarms: never focused, so no Enter
- // presses it, and it asks first (security review of #2779).
- final remove = TextButton(
- key: const Key('team-account-lock-remove'),
- onPressed: _busy ? null : () => unawaited(_askRemove()),
- child: Text(words.remove),
- );
- final confirming = [
- TextButton(
- key: const Key('team-account-lock-remove-back'),
- autofocus: true,
- onPressed: _busy ? null : () => setState(() => _confirming = false),
- child: const Text('Back'),
- ),
- FilledButton(
- key: const Key('team-account-lock-remove-confirm'),
- style: FilledButton.styleFrom(
- backgroundColor: Theme.of(context).colorScheme.error,
- foregroundColor: Theme.of(context).colorScheme.onError,
- ),
- onPressed: _busy ? null : _remove,
- child: const Text('Remove'),
- ),
- ];
- final removeError = _removeError;
- // Remove was refused: the one way left, so nobody is held without an
- // administrator's password (Diego, 2026-11-03).
- final notNow = TextButton(
- key: const Key('team-account-lock-not-now'),
- onPressed: _busy ? null : _notNow,
- child: const Text('Not now'),
- );
- return Center(
- key: const Key('team-account-lock'),
- child: FocusScope(
- autofocus: true,
- child: AlertDialog(
- title: Text(words.title),
- content: SizedBox(
- width: 420,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (_step == _LockStep.intro) ...[
- Text(words.lead, style: body),
- const SizedBox(height: 12),
- Text(words.account, style: body),
- const SizedBox(height: 12),
- Text(words.prompt, style: body),
- const SizedBox(height: 12),
- Text(
- 'Your home folder becomes private to you. Your own agents work as before. '
- 'To remove the account later, run harness team remove.',
- style: muted,
- ),
- ] else ...[
- Row(
- children: [
- if (_step == _LockStep.waiting) ...[
- const SizedBox.square(
- dimension: 14,
- child: CircularProgressIndicator(strokeWidth: 2),
- ),
- const SizedBox(width: 10),
- ],
- Expanded(
- child: Text(
- outcome ?? '',
- key: const Key('team-account-lock-outcome'),
- style: body,
- ),
- ),
- ],
- ),
- if (_step == _LockStep.waiting && _watch.elapsed != null) ...[
- const SizedBox(height: 8),
- Text(
- _Words.sofar(_watch.elapsed!),
- key: const Key('team-account-lock-elapsed'),
- style: muted,
- ),
- ],
- if (_confirming) ...[
- const SizedBox(height: 12),
- Text(
- words.confirmRemove(_confirmSwarms),
- key: const Key('team-account-lock-confirm'),
- style: body,
- ),
- ] else if (removeError != null &&
- (_step == _LockStep.cancelled ||
- _step == _LockStep.cannot)) ...[
- const SizedBox(height: 12),
- Text(
- words.notNowWhy,
- key: const Key('team-account-lock-not-now-why'),
- style: muted,
- ),
- ] else if (_step == _LockStep.cancelled) ...[
- const SizedBox(height: 12),
- Text(words.removeWhy, style: muted),
- ] else if (_step == _LockStep.cannot) ...[
- const SizedBox(height: 12),
- Text(words.removeOnly, style: muted),
- ],
- ],
- if (removeError != null) ...[
- const SizedBox(height: 12),
- Text(
- removeError,
- style: body.copyWith(
- color: Theme.of(context).colorScheme.error,
- ),
- ),
- ],
- ],
- ),
- ),
- actions: _confirming
- ? confirming
- : switch (_step) {
- _LockStep.intro => [
- FilledButton(
- key: const Key('team-account-lock-continue'),
- autofocus: true,
- onPressed: _busy ? null : _start,
- child: const Text('Continue'),
- ),
- ],
- // Never without a way on (Scholes, 2026-11-04): Remove
- // asks first, and Try again starts nothing while setup
- // runs.
- _LockStep.waiting => [
- remove,
- FilledButton(
- key: const Key('team-account-lock-retry'),
- autofocus: true,
- onPressed: _busy ? null : _tryAgainWaiting,
- child: const Text('Try again'),
- ),
- ],
- _LockStep.retry => [retry],
- _LockStep.cancelled => [
- if (removeError != null) notNow,
- remove,
- retry,
- ],
- _LockStep.cannot => [if (removeError != null) notNow, remove],
- },
- ),
- ),
- );
- }
-}
diff --git a/desktop/test/native_toolbar_sync_test.dart b/desktop/test/native_toolbar_sync_test.dart
index fb3d0cc90..29577dff5 100644
--- a/desktop/test/native_toolbar_sync_test.dart
+++ b/desktop/test/native_toolbar_sync_test.dart
@@ -104,21 +104,6 @@ class _SharesDaemon extends WsConn {
}
}
-/// This computer's daemon wanting its Harness Team account set up.
-class _TeamDaemon extends _SharesDaemon {
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) async {
- if (type == 'super_tabs' && payload['action'] == 'teamSetupCheck') {
- return {'ok': true, 'state': 'wanted'};
- }
- return super.request(type, payload: payload, timeout: timeout);
- }
-}
-
/// A roster as `shares` lists it: [owner]'s tab with [harnesses] harnesses,
/// shared from [ownerMachine]. The owner's own roster names its desk tab
/// ([tabId]); a member's desk tab is derived from [sharedTabId] ([_memberTab]).
@@ -855,64 +840,4 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
});
-
- // Review of #2779: the menu bar, its key equivalents and the tab row reach
- // the workspace over the channel, not through Flutter's focus, so the lock's
- // barrier alone did not hold them.
- testWidgets(
- 'the Team account setup lock greys the menus and the tab row, and drops their actions',
- (tester) async {
- final app = _App(daemon: _TeamDaemon())
- ..teamAccountHereForTest = true
- ..currentUser = const CurrentUserProfile(
- id: 'owner',
- email: '[email protected]',
- );
- addTearDown(app.dispose);
- final first = app.activeSwarmId;
- app.newSwarm(name: 'Other');
- final other = app.activeSwarmId;
- expect(other, isNot(first));
- await mount(tester, app, nativeTabs: true);
- await tester.pumpAndSettle();
- expect(updates().last['enabled'], isTrue);
-
- await app.offerTeamAccount('join', tabId: 'tab-1');
- await tester.pumpAndSettle();
- expect(app.teamSetupLocked, isTrue);
- expect(updates().last['enabled'], isFalse);
- expect(updates().last['stripEnabled'], isFalse);
-
- Future<void> native(String method, Map args) =>
- tester.binding.defaultBinaryMessenger.handlePlatformMessage(
- 'harness/swarm_tabs',
- const StandardMethodCodec().encodeMethodCall(
- MethodCall(method, args),
- ),
- (_) {},
- );
- // A row click or key equivalent that arrives anyway does nothing.
- unawaited(native('select', {'id': first}));
- await tester.pumpAndSettle();
- unawaited(
- native('rowAction', {
- 'method': 'select',
- 'arguments': {'id': first},
- }),
- );
- await tester.pumpAndSettle();
- unawaited(native('keymapCommand', {'command': 'tab.previous'}));
- await tester.pumpAndSettle();
- expect(app.activeSwarmId, other);
-
- await app.teamAccountMade();
- await tester.pumpAndSettle();
- expect(updates().last['enabled'], isTrue);
- expect(updates().last['stripEnabled'], isTrue);
- unawaited(native('select', {'id': first}));
- await tester.pumpAndSettle();
- expect(app.activeSwarmId, first);
- await tester.pumpWidget(const SizedBox());
- },
- );
}
diff --git a/desktop/test/super_tab_add_computers_test.dart b/desktop/test/super_tab_add_computers_test.dart
index 54d2a20ec..6e9a89bc3 100644
--- a/desktop/test/super_tab_add_computers_test.dart
+++ b/desktop/test/super_tab_add_computers_test.dart
@@ -401,6 +401,8 @@ void main() {
},
);
+ // Swarm v3 makes no Team account (#4221): a computer without one is short of nothing, while one whose existing Team
+ // account fails its check still says so.
testWidgets(
'an added computer without a working Team account says only your projects run there',
(tester) async {
@@ -424,10 +426,11 @@ void main() {
});
await openBox(tester, c, f.app);
// A word or two on the row, the whole reason on hover.
- expect(inRow('studio', 'added · not set up'), findsOneWidget);
+ expect(inRow('studio', 'added'), findsOneWidget);
+ expect(find.textContaining('not set up'), findsNothing);
expect(
find.byTooltip('No Team account yet, so only your projects run here.'),
- findsOneWidget,
+ findsNothing,
);
expect(inRow('air', 'added · check failed'), findsOneWidget);
expect(
@@ -440,37 +443,6 @@ void main() {
},
);
- testWidgets(
- 'this Mac\'s failed Team account setup is said in plain words on its row',
- (tester) async {
- final (:f, :c) = await swarm((f) {
- f.app.teamAccountHereForTest = true;
- f.connection.teamSetup = {
- 'state': 'failed',
- 'detail': 'dscl exited 64',
- };
- f.connection.server.state['machines'] = [
- {
- 'machineId': 'm',
- 'name': f.app.stateOf('m')!.machine.displayName,
- 'contributorId': 'owner',
- 'teamWork': {'allowed': false, 'code': 'TEAM_ACCOUNT_REQUIRED'},
- },
- ];
- });
- await openBox(tester, c, f.app);
- expect(inRow('m', 'added · setup failed'), findsOneWidget);
- expect(
- find.byTooltip(
- 'Team account setup failed, so only your projects run here.',
- ),
- findsOneWidget,
- );
- expect(find.textContaining('dscl'), findsNothing);
- await close(tester, f, c);
- },
- );
-
testWidgets(
'losing write access while the box is open takes its rows away and says why',
(tester) async {
@@ -832,7 +804,7 @@ void main() {
// The PR's pictures, light and dark, over in-memory Swarms only: the first
// box with this Mac not added, several computers, all added, offline rows,
- // Team account setup failed, Dee's Swarm with six computers, and a row
+ // a Team account's failed check, Dee's Swarm with six computers, and a row
// that could not be added.
Map<String, dynamic> pool(String id, String name, [String? teamCode]) => {
'machineId': id,
@@ -881,13 +853,8 @@ void main() {
},
),
(
- '5-team-account-setup-failed',
+ '5-team-account-check-failed',
(f) {
- f.app.teamAccountHereForTest = true;
- f.connection.teamSetup = {
- 'state': 'failed',
- 'detail': 'dscl exited 64',
- };
computer(f, 'studio', 'Studio');
computer(f, 'mini', 'Mac mini');
f.connection.server.state['machines'] = [
diff --git a/desktop/test/super_tab_computer_move_shots_test.dart b/desktop/test/super_tab_computer_move_shots_test.dart
index 11584be81..605c12068 100644
--- a/desktop/test/super_tab_computer_move_shots_test.dart
+++ b/desktop/test/super_tab_computer_move_shots_test.dart
@@ -1,5 +1,5 @@
-// Task #3122 (Scholes, 11-05): a computer moved from kelvin's account, whose Harness Team account still works for him, for
-// the pull request's pictures. Writes nothing unless COMPUTER_MOVE_SHOTS names a folder.
+// Task #3122 (Scholes, 11-05): a computer moved from kelvin's account, for the pull request's pictures. Writes nothing
+// unless COMPUTER_MOVE_SHOTS names a folder.
import 'dart:io';
import 'package:flutter/material.dart';
@@ -8,26 +8,11 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/machines.dart';
import 'support/capture.dart';
-import 'support/rename_connection.dart';
import 'support/super_tab_fixture.dart';
import 'swarm_state_test.dart' show createApp;
final shots = Platform.environment['COMPUTER_MOVE_SHOTS'];
-class _TeamDaemon extends RenameConnection {
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) {
- if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {
- return Future.value({'ok': true, 'state': 'exists'});
- }
- return super.request(type, payload: payload, timeout: timeout);
- }
-}
-
void main() {
setUpAll(() => loadCaptureFonts(shots));
@@ -42,9 +27,7 @@ void main() {
tester.view.devicePixelRatio = 2;
tester.view.physicalSize = const Size(1240, 520);
addTearDown(tester.view.reset);
- final daemon = _TeamDaemon();
- final app = createApp(connectionForTest: (_) => daemon, connected: true)
- ..teamAccountHereForTest = true;
+ final app = createApp(connected: true);
app.machineStates['m']!.localOnly = true;
final server = ConversationServer();
(server.state['people'] as List).add({
diff --git a/desktop/test/super_tab_computer_move_test.dart b/desktop/test/super_tab_computer_move_test.dart
index d1c123e3c..d1dd7e6da 100644
--- a/desktop/test/super_tab_computer_move_test.dart
+++ b/desktop/test/super_tab_computer_move_test.dart
@@ -1,6 +1,5 @@
// One row per computer (#3122, Scholes 11-05): a computer signed in as another account shows once, under that account,
-// saying who it was before. Its Harness Team account may still serve the old account: the Swarm then says it has none,
-// while this Mac's daemon says it exists. The row says so in plain words, and Repair signs it in again for this account.
+// saying who it was before. A Harness Team account it still has that cannot join says why, with Retry (#3215).
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/machines.dart';
@@ -9,10 +8,8 @@ import 'support/rename_connection.dart';
import 'support/super_tab_fixture.dart';
import 'swarm_state_test.dart' show createApp;
-/// This Mac's daemon: what it says of its Harness Team account, and every setup it is asked for.
+/// This Mac's daemon: what it says of its Harness Team account's join, and every retry it is asked for.
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;
@@ -23,9 +20,6 @@ class _TeamDaemon extends RenameConnection {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
}) {
- 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});
}
@@ -35,11 +29,6 @@ class _TeamDaemon extends RenameConnection {
hostRunning = true;
return Future.value({'ok': true});
}
- if (type == 'super_tabs' && payload['action'] == 'teamSetup') {
- setups.add(Map.of(payload));
- status = {'ok': true, 'state': 'running'};
- return Future.value({'ok': true, 'state': 'started'});
- }
return super.request(type, payload: payload, timeout: timeout);
}
}
@@ -131,58 +120,9 @@ void main() {
},
);
- testWidgets(
- 'a Harness Team account serving another account reads so on this Mac\'s row, and Repair signs it in again for this account',
- (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,
- );
- expect(
- _text(tester, 'super-machine-problem-m'),
- "Teammates' agents paused: Harness Team on this computer works for another account",
- );
- final repair = find.byKey(const ValueKey('super-machine-team-setup-m'));
- expect(
- find.descendant(of: repair, matching: find.text('Repair')),
- findsOneWidget,
- );
-
- await tester.tap(repair);
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('team-account-setup-continue')));
- await tester.pumpAndSettle();
- expect(daemon.setups, [
- {'action': 'teamSetup', 'reason': 'manual', 'signInAgain': true},
- ]);
- // Once the dialog closes, the row reads the daemon again: the setup is running now.
- await tester.tap(find.byKey(const Key('team-account-setup-done')));
- await tester.pumpAndSettle();
- expect(
- _text(tester, 'super-machine-problem-m'),
- "Teammates' agents paused: setting up",
- );
- await _unmount(tester, c);
- app.dispose();
- },
- );
-
// Scholes, 11-05: right after Add machine the row read "not set up" with Set up for a few seconds, until the Mac's own
// Harness Team account joined the Swarm.
- testWidgets('a Mac whose Harness Team account is joining says so, with no Set up', (
+ testWidgets('a Mac whose Harness Team account is joining says so, with no button', (
tester,
) async {
final daemon = _TeamDaemon();
@@ -207,42 +147,13 @@ void main() {
"Teammates' agents paused: Harness Team is joining",
);
expect(
- find.byKey(const ValueKey('super-machine-team-setup-m')),
+ find.byKey(const ValueKey('super-machine-team-retry-m')),
findsNothing,
);
await _unmount(tester, c);
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', (
@@ -270,8 +181,12 @@ void main() {
_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'));
+ final retry = find.byKey(const ValueKey('super-machine-team-retry-m'));
expect(find.descendant(of: retry, matching: find.text('Retry')), findsOneWidget);
+ // Amon, 11-05: the design system's own secondary action, a themed outlined button as drawn everywhere else.
+ final button = tester.widget<ButtonStyleButton>(retry);
+ expect(button, isA<OutlinedButton>());
+ expect(button.style, isNull);
await tester.tap(retry);
await tester.pumpAndSettle();
expect(daemon.joinRetries, 1);
@@ -304,7 +219,7 @@ void main() {
_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.tap(find.byKey(const ValueKey('super-machine-team-retry-m')));
await tester.pumpAndSettle();
expect(daemon.joinRetries, 1);
expect(
@@ -314,9 +229,4 @@ void main() {
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_import_agent_test.dart b/desktop/test/super_tab_import_agent_test.dart
index 57216b333..fd9bfe5b5 100644
--- a/desktop/test/super_tab_import_agent_test.dart
+++ b/desktop/test/super_tab_import_agent_test.dart
@@ -1271,7 +1271,8 @@ void main() {
expect(find.text("What openharness's members will read"), findsNothing);
}, variant: mac);
- testWidgets('no Team account for this Mac says how to set one up', (
+ // Swarm v3 has no Team accounts (#4221): nothing offers to set one up.
+ testWidgets('no Team account for this Mac offers no Set up', (
tester,
) async {
final f = await roster(tester);
@@ -1282,14 +1283,7 @@ void main() {
await openImport(tester);
expect(find.text(kImportNeedsTeamAccount), findsOneWidget);
expect(find.textContaining('fix-fix'), findsNothing);
- await tester.tap(find.text('Set up Harness Team'));
- await tester.pumpAndSettle();
- expect(
- find.textContaining(
- RegExp(r'^Set up Harness Team on this (Mac|computer)$'),
- ),
- findsOneWidget,
- );
+ expect(find.text('Set up Harness Team'), findsNothing);
expect(f.server.posts, isEmpty);
}, variant: mac);
});
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index b84a9a6fd..a3a392066 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/first_task.dart';
import 'package:harness/core/models.dart';
+import 'package:harness/core/permission_modes.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/core/launch_setup.dart';
import 'package:harness/notify/system_notifications.dart';
@@ -65,16 +66,6 @@ class SuperTabFixtureConnection extends WsConn {
/// from before setup reported it.
int? maxAvailableAgents = 16;
- /// What this Mac's daemon remembers of its Harness Team account setup
- /// (`teamSetupStatus`); null answers as a daemon too old to say.
- Map<String, dynamic>? teamSetup;
-
- /// What this Mac's daemon answers whether its Harness Team account is wanted
- /// (`teamSetupCheck`); null answers as a daemon too old to say.
- Map<String, dynamic>? teamCheck;
-
- /// What starting the account's setup answers (`teamSetup`, `manual`).
- Map<String, dynamic> teamRun = {'state': 'started'};
bool loseCreate = false, loseJoin = false;
/// Refuses the next join as the backend would, before anything is written.
@@ -200,15 +191,6 @@ class SuperTabFixtureConnection extends WsConn {
throw backendFailure!;
}
if (payload['action'] == 'wake') return {'ok': true};
- if (payload['action'] == 'teamSetupStatus') {
- if (teamSetup case final setup?) return {'ok': true, ...setup};
- throw const SuperTabFailure('INVALID_REQUEST', 'Unknown action.');
- }
- if (payload['action'] == 'teamSetup') return {'ok': true, ...teamRun};
- if (payload['action'] == 'teamSetupCheck') {
- if (teamCheck case final check?) return {'ok': true, ...check};
- throw const SuperTabFailure('INVALID_REQUEST', 'Unknown action.');
- }
if (payload['action'] == 'prepareContribution') {
if (prepared.add(payload['operationId']) || keepPreparing) {
return {'ok': true, 'state': 'preparing'};
@@ -536,7 +518,9 @@ class SuperTabLaunchFixture {
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
- 'Swarm members with no full mode retain their supported launch behavior',
+ // Swarm v3 (task #4215): no mode is forced, so another engine's Swarm
+ // member launches exactly as its ordinary harness does.
+ 'Swarm members on other engines launch as their ordinary harness does',
() async {
for (final engine in ['opencode', 'hermes']) {
final f = SuperTabLaunchFixture();
@@ -552,20 +536,26 @@ void main() {
final request = f.connection.calls
.firstWhere((c) => c.$1 == 'agent_create')
.$2;
- expect(request['permissionMode'], isNull);
- expect(request['bypassPermission'], isTrue);
- expect(
- box.agentSettingsFor(engine).map((o) => o.id),
- isNot(contains(NewHarnessController.permissionsId)),
- );
+ final settings = box.agentSettingsFor(engine).map((o) => o.id);
+ if (engine == 'hermes') {
+ expect(request['permissionMode'], isNull);
+ expect(request['bypassPermission'], isFalse);
+ expect(settings, isNot(contains(NewHarnessController.permissionsId)));
+ } else {
+ expect(settings, contains(NewHarnessController.permissionsId));
+ expect(request['permissionMode'], box.mode);
+ expect(request['bypassPermission'], permissionModeApproves(box.mode));
+ }
}
},
);
for (final engine in ['claude', 'codex']) {
for (final kind in ['new Swarm', 'new project', 'member']) {
+ // Swarm v3 (task #4215): a Swarm agent starts with the mode the person
+ // chose in Cmd-N, as any harness does; none is forced.
test(
- '$kind launches $engine in full mode without permission choices',
+ '$kind launches $engine in the permission mode the person chose',
() async {
final f = SuperTabLaunchFixture();
await f.app.agentPreference.selectPermissionMode(engine, 'ask');
@@ -583,12 +573,9 @@ void main() {
);
expect(
box.agentSettingsFor(engine).map((o) => o.id),
- isNot(contains(NewHarnessController.permissionsId)),
+ contains(NewHarnessController.permissionsId),
);
- box.advancedOpen = true;
- expect(box.fields, isNot(contains(NewHarnessField.mode)));
- box.openLaunchSetting(NewHarnessField.mode);
- expect(box.field, isNot(NewHarnessField.mode));
+ expect(box.mode, 'ask');
expect(
await box.create(),
NewHarnessOutcome.created,
@@ -597,7 +584,8 @@ void main() {
final request = f.connection.calls
.firstWhere((c) => c.$1 == 'agent_create')
.$2;
- expect(request['permissionMode'], 'full');
+ expect(request['permissionMode'], 'ask');
+ expect(request['bypassPermission'], isFalse);
expect(request['swarmRole'], kind == 'member' ? 'dev' : 'lead');
expect(
request['swarmSkillMode'],
@@ -1287,7 +1275,7 @@ void main() {
expect(mac.engineRefusals, {
'codex': 'Codex isn’t offered on Diego MacBook',
});
- expect((mac.startable, mac.inTeam('claude')), (true, false));
+ expect(mac.startable, isTrue);
box.chooseLeadMachine('diego-mac');
// The engine it can run there, on the Mac itself, as the server said.
expect(box.engine, 'claude');
@@ -1304,32 +1292,6 @@ void main() {
);
});
- test('each engine runs where the server says: Codex in the Team account, '
- 'Claude Code on the Mac whose account signed it out', () async {
- final f = SuperTabLaunchFixture();
- addDiego(f);
- knownRepo(f);
- f.connection.server.state['machines'] = rows({
- 'claude': {'machineId': 'diego-mac'},
- 'codex': {'machineId': 'diego-team'},
- });
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
- final box = await f.box(newProject: true, engine: 'codex', lead: null);
- box.chooseLeadMachine('diego-mac');
- expect(box.engine, 'codex');
- expect(
- box.leadLine,
- startsWith('Product Manager on Diego MacBook’s Team account · Codex'),
- );
- box.focusField(NewHarnessField.agent);
- box.accept(box.options.where((o) => o.id == 'claude').single);
- expect(
- box.leadLine,
- startsWith('Product Manager on Diego MacBook · Claude Code'),
- );
- expect(box.leadBlocked, isNull);
- });
-
test('with every engine refused, the Mac cannot be chosen and says why '
'once', () async {
final f = SuperTabLaunchFixture();
diff --git a/desktop/test/super_tab_personal_lead_test.dart b/desktop/test/super_tab_personal_lead_test.dart
index 36d90aeab..8331394c0 100644
--- a/desktop/test/super_tab_personal_lead_test.dart
+++ b/desktop/test/super_tab_personal_lead_test.dart
@@ -98,6 +98,10 @@ void main() {
expect(create['cwd'], '/Users/huy/games');
expect(create['swarmRole'], 'lead');
expect(create['engine'], 'claude');
+ // Swarm v3 (task #4215): no dialog, so no mode: the PM starts with its
+ // owner's own permission settings.
+ expect(create.containsKey('permissionMode'), isFalse);
+ expect(create['bypassPermission'], isFalse);
final join = f.connection.joins.single['command'] as Map;
expect(join['lead'], isTrue);
expect(join['conversationId'], games);
diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dart
index 0d2d4e8a6..0cc3a7ac4 100644
--- a/desktop/test/super_tab_team_machine_test.dart
+++ b/desktop/test/super_tab_team_machine_test.dart
@@ -2,45 +2,15 @@
// second contribution, its pool naming the Mac as `hostMachineId`, and the Swarm shows the Mac alone. Its agents read as
// on the Mac; teammates read the account's availability, which runs while the owner is away from the Mac; the only new
// words are one line when teammates' agents cannot run there.
-import 'dart:io';
-
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/agent_details.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/machines.dart';
-import 'support/capture.dart';
-import 'support/rename_connection.dart';
import 'support/super_tab_fixture.dart';
-import 'swarm_state_test.dart' show createApp;
const _offlineAge = 10 * 60 * 1000;
-/// This Mac's daemon, answering what it remembers of its Harness Team account
-/// setup (`teamSetupStatus`); no socket is opened.
-class _TeamDaemon extends RenameConnection {
- Map<String, dynamic> status = {'ok': true, 'state': 'none'};
- final asked = <Map<String, dynamic>>[];
-
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) {
- if (type == 'super_tabs' && payload['action'] == 'teamSetup') {
- asked.add(Map.of(payload));
- return Future.value({'ok': true, 'state': 'exists'});
- }
- if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {
- asked.add(Map.of(payload));
- return Future.value(status);
- }
- return super.request(type, payload: payload, timeout: timeout);
- }
-}
-
Map<String, dynamic> _pool(
String id, {
String name = 'MacBook Pro',
@@ -122,7 +92,6 @@ String? _problemText(WidgetTester tester, String id) =>
tester.widget<Text>(_problem(id)).data;
void main() {
- setUpAll(() => loadCaptureFonts(Platform.environment['TEAM_RESTART_SHOTS']));
testWidgets(
'a Mac and its Harness Team account are one row, with every agent of both under it',
(tester) async {
@@ -281,264 +250,6 @@ void main() {
await _unmount(tester, c);
});
- testWidgets(
- 'on this Mac\'s own row, its person can set the Harness Team account up there; nobody else, nowhere else',
- (tester) async {
- final app = createApp(connected: true)..teamAccountHereForTest = true;
- app.machineStates['m']!.localOnly = true;
- Future<bool> button({
- String account = 'owner',
- String id = 'm',
- String code = 'TEAM_ACCOUNT_REQUIRED',
- }) async {
- final server = _swarm();
- server.state['machines'] = [
- _pool(
- id,
- contributor: account == 'peer' ? 'owner' : 'owner',
- teamWork: _refused(code),
- ),
- ];
- final c = server.controller(account: account);
- await c.refresh();
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: SuperTabMachines(
- controller: c,
- app: app,
- onAddAgent: (_) {},
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- final shown = find
- .byKey(ValueKey('super-machine-team-setup-$id'))
- .evaluate()
- .isNotEmpty;
- await _unmount(tester, c);
- return shown;
- }
-
- expect(await button(), isTrue);
- // A teammate reads the Mac's line, never its button; another Mac's row has none; nor a privacy refusal.
- expect(await button(account: 'peer'), isFalse);
- expect(await button(id: 'other'), isFalse);
- expect(await button(code: 'PRIVACY_CHECK_FAILED'), isFalse);
- app.teamAccountHereForTest = false;
- expect(await button(), isFalse);
- app.dispose();
- },
- );
-
- testWidgets(
- 'an offline Team account offers its local owner Restart through the standard setup flow',
- (tester) async {
- final shots = Platform.environment['TEAM_RESTART_SHOTS'];
- final previousBrightness = grid.AppTheme.brightness.value;
- addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
- final daemon = _TeamDaemon()..status = {'ok': true, 'state': 'exists'};
- final app = createApp(connectionForTest: (_) => daemon, connected: true)
- ..teamAccountHereForTest = true;
- app.machineStates['m']!.localOnly = true;
- Future<void> mount({
- String account = 'owner',
- String id = 'm',
- bool hostOffline = false,
- Brightness brightness = Brightness.light,
- }) async {
- grid.AppTheme.brightness.value = brightness;
- final server = _swarm();
- server.state['machines'] = [
- _pool(id, contributor: 'owner', age: hostOffline ? _offlineAge : 0),
- _pool(
- '$id-team',
- contributor: 'owner',
- host: id,
- age: _offlineAge,
- teamWork: _refused('MACHINE_OFFLINE'),
- ),
- ];
- final c = server.controller(account: account);
- await c.refresh();
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- home: Scaffold(
- body: SuperTabMachines(
- controller: c,
- app: app,
- onAddAgent: (_) {},
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- final button = find.byKey(ValueKey('super-machine-team-setup-$id'));
- if (account == 'owner' && id == 'm' && !hostOffline) {
- expect(
- _problemText(tester, id),
- "Teammates' agents paused: Harness Team account offline",
- );
- expect(
- find.descendant(of: button, matching: find.text('Restart')),
- findsOneWidget,
- );
- expect(tester.widget(button), isA<OutlinedButton>());
- await captureWindow(tester, shots, 'team-offline-${brightness.name}');
- await tester.tap(button);
- await tester.pumpAndSettle();
- await tester.tap(
- find.byKey(const Key('team-account-setup-continue')),
- );
- await tester.pumpAndSettle();
- expect(daemon.asked.where((a) => a['action'] == 'teamSetup').last, {
- 'action': 'teamSetup',
- 'reason': 'manual',
- 'restart': true,
- });
- await tester.tap(find.byKey(const Key('team-account-setup-done')));
- await tester.pumpAndSettle();
- } else {
- expect(button, findsNothing);
- }
- await _unmount(tester, c);
- }
-
- await mount();
- await mount(brightness: Brightness.dark);
- await mount(account: 'peer');
- await mount(id: 'remote');
- await mount(hostOffline: true);
- app.dispose();
- },
- );
-
- // Scholes, 2026-10-29: a Mac whose person cancelled the password prompt, or whose setup failed, said only "not set up".
- testWidgets(
- 'this Mac\'s row says why it has no Harness Team account, for its person alone, with Set up to try again',
- (tester) async {
- final daemon = _TeamDaemon();
- final app = createApp(connectionForTest: (_) => daemon, connected: true)
- ..teamAccountHereForTest = true;
- app.machineStates['m']!.localOnly = true;
- Future<String?> line(
- Map<String, dynamic> status, {
- String account = 'owner',
- }) async {
- daemon.status = status;
- final server = _swarm();
- server.state['machines'] = [
- _pool(
- 'm',
- contributor: 'owner',
- teamWork: _refused('TEAM_ACCOUNT_REQUIRED'),
- ),
- ];
- final c = server.controller(account: account);
- await c.refresh();
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: SuperTabMachines(
- controller: c,
- app: app,
- onAddAgent: (_) {},
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- final text = _problemText(tester, 'm');
- if (account == 'owner') {
- expect(
- find.byKey(const ValueKey('super-machine-team-setup-m')),
- findsOneWidget,
- );
- }
- await _unmount(tester, c);
- return text;
- }
-
- expect(
- await line({'ok': true, 'state': 'declined'}),
- "Teammates' agents paused: setup was cancelled",
- );
- expect(
- await line({
- 'ok': true,
- 'state': 'failed',
- 'detail': 'launchd would not start it.',
- }),
- "Teammates' agents paused: setup failed: launchd would not start it",
- );
- expect(
- await line({'ok': true, 'state': 'running'}),
- "Teammates' agents paused: setting up",
- );
- expect(
- await line({'ok': true, 'state': 'none'}),
- "Teammates' agents paused: not set up",
- );
- // A daemon from before it could say, and one that cannot answer: as before.
- expect(
- await line({'error': 'INVALID_REQUEST'}),
- "Teammates' agents paused: not set up",
- );
- // A teammate reads the Mac's own line from the Swarm; this Mac's daemon is never asked for them.
- final before = daemon.asked.length;
- expect(
- await line({'ok': true, 'state': 'declined'}, account: 'peer'),
- "Teammates' agents paused: not set up",
- );
- expect(daemon.asked.length, before);
- app.dispose();
- },
- );
-
- // Local Team account run, 2026-10-28: after `harness team remove` its pool stays listed, and the Mac's owner read
- // "Harness Team account offline" with no way to set one up again.
- testWidgets(
- 'a removed Harness Team account leaves its Mac a Mac without one: not set up, and Set up for its owner',
- (tester) async {
- final app = createApp(connected: true)..teamAccountHereForTest = true;
- app.machineStates['m']!.localOnly = true;
- final server = _swarm();
- server.state['machines'] = [
- _pool(
- 'm',
- contributor: 'owner',
- teamWork: _refused('TEAM_ACCOUNT_REQUIRED'),
- ),
- _pool(
- 'm-team',
- contributor: 'owner',
- host: 'm',
- teamWork: _refused('TEAM_ACCOUNT_REQUIRED'),
- ),
- ];
- final c = server.controller(account: 'owner');
- await c.refresh();
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: SuperTabMachines(controller: c, app: app, onAddAgent: (_) {}),
- ),
- ),
- );
- await tester.pumpAndSettle();
- expect(_problemText(tester, 'm'), "Teammates' agents paused: not set up");
- expect(
- find.byKey(const ValueKey('super-machine-team-setup-m')),
- findsOneWidget,
- );
- await _unmount(tester, c);
- app.dispose();
- },
- );
-
// Local Team account run, 2026-10-28 (group #646, item 5): a teammate's Lead computer, never added to the Swarm, read
// "Unavailable machine" with an empty dot. Named by its owner, as the Swarm knows no name for it.
testWidgets(
diff --git a/desktop/test/swarm_v3_join_integration_test.dart b/desktop/test/swarm_v3_join_integration_test.dart
index 73a2d462b..2e3ce3e56 100644
--- a/desktop/test/swarm_v3_join_integration_test.dart
+++ b/desktop/test/swarm_v3_join_integration_test.dart
@@ -10,7 +10,6 @@ void main() {
final f = SuperTabLaunchFixture();
f.app.status = AppStatus.authenticated;
f.app.teamAccountHereForTest = true;
- f.connection.teamCheck = {'state': 'wanted'};
f.connection.server.state['people'] = [
{'id': 'boss', 'email': '[email protected]', 'role': 'owner'},
{'id': 'owner', 'email': '[email protected]', 'role': 'collaborator'},
diff --git a/desktop/test/team_account_lock_test.dart b/desktop/test/team_account_lock_test.dart
deleted file mode 100644
index 9bae3b116..000000000
--- a/desktop/test/team_account_lock_test.dart
+++ /dev/null
@@ -1,1349 +0,0 @@
-import 'dart:async';
-
-import 'dart:io';
-
-import 'package:flutter/foundation.dart';
-import 'package:flutter/gestures.dart' show kSecondaryMouseButton;
-import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_riverpod/flutter_riverpod.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/app_shell.dart';
-import 'package:harness/auth/auth_session.dart';
-import 'package:harness/auth/cli_login.dart';
-import 'package:harness/core/config.dart';
-import 'package:harness/core/machine_resources.dart';
-
-import 'package:harness/core/models.dart';
-import 'package:harness/settings/settings_screen.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/state/app_state.dart';
-import 'package:harness/super_tabs/controller.dart' show SuperTabController;
-import 'package:harness/super_tabs/machines.dart';
-import 'package:harness/super_tabs/swarm_switcher.dart' show PersonalSwarm;
-import 'package:harness/super_tabs/team_account_setup.dart';
-
-import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
-import 'support/capture.dart';
-import 'support/rename_connection.dart';
-import 'swarm_state_test.dart' show createApp;
-
-/// This Mac's daemon for the Harness Team account's actions; no socket is
-/// opened, and nothing is set up or signed out.
-class _Daemon extends RenameConnection {
- final asked = <String>[];
-
- /// `teamSetupCheck`: whether the account is wanted here.
- Map<String, dynamic> check = {'ok': true, 'state': 'wanted'};
-
- /// `teamSetup` (`manual`): what starting it answers.
- Map<String, dynamic> run = {'ok': true, 'state': 'started'};
-
- /// `teamSetupStatus`, in turn; the last one repeats.
- final statuses = <Map<String, dynamic>>[
- {'ok': true, 'state': 'running'},
- ];
-
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) async {
- final action = '${payload['action']}';
- if (type == 'super_tabs' && action.startsWith('teamSetup')) {
- asked.add(action);
- return switch (action) {
- 'teamSetupCheck' => check,
- 'teamSetup' => run,
- 'teamSetupStatus' =>
- statuses.length > 1 ? statuses.removeAt(0) : statuses.single,
- _ => {'ok': true},
- };
- }
- return super.request(type, payload: payload, timeout: timeout);
- }
-}
-
-/// Never the real CLI: nothing here may sign this Mac out.
-class _FakeCli extends CliLogin {
- @override
- Future<void> logout() async {}
-
- @override
- Future<CliAuthStatus> checkStatus() async => CliAuthStatus(loggedIn: true);
-}
-
-/// Set to a folder to write the PR's pictures there.
-final shots = Platform.environment['TEAM_ACCOUNT_LOCK_SHOTS'];
-
-const _wrongPassword =
- 'The Harness Team account was not finished: The administrator user name or '
- 'password was incorrect. (-60005). Run `harness team setup` again; it repairs what is there.';
-
-void main() {
- TestWidgetsFlutterBinding.ensureInitialized();
- setUpAll(() => loadCaptureFonts(shots));
- late _Daemon daemon;
- late AppNotifier app;
-
- setUp(() {
- daemon = _Daemon();
- app = createApp(connectionForTest: (_) => daemon, connected: true);
- app.currentUser = const CurrentUserProfile(
- id: 'owner',
- email: '[email protected]',
- );
- app.machineStates['m']!.localOnly = true;
- app.teamAccountHereForTest = true;
- });
- tearDown(() => app.dispose());
-
- final navigator = GlobalKey<NavigatorState>();
- var taps = 0, shortcuts = 0;
- late FocusNode behind;
-
- /// The app's window as app_shell.dart builds it: the lock above the
- /// Navigator, so it covers every route and dialog too.
- Future<void> window(WidgetTester tester, AppNotifier app) async {
- taps = 0;
- shortcuts = 0;
- behind = FocusNode(debugLabel: 'behind');
- addTearDown(behind.dispose);
- await tester.pumpWidget(
- MaterialApp(
- navigatorKey: navigator,
- builder: (context, child) => TeamAccountSetupLock(
- app: app,
- operatingSystem: 'macos',
- child: child!,
- ),
- home: Scaffold(
- body: CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.keyK, meta: true): () =>
- shortcuts++,
- },
- child: Column(
- children: [
- TextButton(
- key: const Key('behind-button'),
- focusNode: behind,
- autofocus: true,
- onPressed: () => taps++,
- child: const Text('Behind'),
- ),
- const TextField(key: Key('behind-field')),
- ],
- ),
- ),
- ),
- ),
- );
- await tester.pump();
- }
-
- Future<void> lock(WidgetTester tester) async {
- await app.offerTeamAccount('join', tabId: 'tab-1');
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- }
-
- /// Whether the focused widget sits under [finder].
- bool focusedIn(Finder finder) {
- final focused = FocusManager.instance.primaryFocus?.context;
- if (focused == null) return false;
- return finder.evaluate().any(
- (element) =>
- element == focused ||
- (focused as Element).debugGetDiagnosticChain().contains(element),
- );
- }
-
- /// Every label in the semantics tree a screen reader walks.
- List<String> spoken(WidgetTester tester) {
- final labels = <String>[];
- void walk(SemanticsNode node) {
- if (node.label.isNotEmpty) labels.add(node.label);
- node.visitChildren((child) {
- walk(child);
- return true;
- });
- }
-
- final root =
- tester.binding.rootPipelineOwner.semanticsOwner?.rootSemanticsNode;
- if (root != null) walk(root);
- for (final view in tester.binding.renderViews) {
- final node = view.owner?.semanticsOwner?.rootSemanticsNode;
- if (node != null) walk(node);
- }
- return labels;
- }
-
- String outcome(WidgetTester tester) => tester
- .widget<Text>(find.byKey(const Key('team-account-lock-outcome')))
- .data!;
-
- testWidgets('unlocked, it is not there and the app takes input', (
- tester,
- ) async {
- await window(tester, app);
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await tester.tap(find.byKey(const Key('behind-button')));
- expect(taps, 1);
- });
-
- testWidgets(
- 'locked, nothing behind it takes a click, a key or focus, a dialog included',
- (tester) async {
- final semantics = tester.ensureSemantics();
- await window(tester, app);
- // A dialog open before the join, as a menu item's would be.
- var dialogTaps = 0;
- navigator.currentState!.push(
- DialogRoute<void>(
- context: navigator.currentContext!,
- builder: (_) => Dialog(
- child: TextButton(
- key: const Key('dialog-button'),
- onPressed: () => dialogTaps++,
- child: const Text('In a dialog'),
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- await lock(tester);
-
- await tester.tap(
- find.byKey(const Key('behind-button')),
- warnIfMissed: false,
- );
- await tester.tap(
- find.byKey(const Key('dialog-button')),
- warnIfMissed: false,
- );
- await tester.tap(
- find.byKey(const Key('behind-field')),
- warnIfMissed: false,
- );
- await tester.pump();
- expect(taps, 0);
- expect(dialogTaps, 0);
-
- for (var i = 0; i < 8; i++) {
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- expect(focusedIn(find.byKey(const Key('team-account-lock'))), isTrue);
- }
- // Something behind asks for focus by itself (a terminal on output, a
- // dialog opening): it does not get it, and Enter presses nothing there.
- behind.requestFocus();
- await tester.pump();
- expect(focusedIn(find.byKey(const Key('team-account-lock'))), isTrue);
- navigator.currentState!.push(
- DialogRoute<void>(
- context: navigator.currentContext!,
- builder: (_) => Dialog(
- child: TextButton(
- key: const Key('late-dialog-button'),
- autofocus: true,
- onPressed: () => dialogTaps++,
- child: const Text('Opened while locked'),
- ),
- ),
- ),
- );
- await tester.pump();
- await tester.pump();
- expect(focusedIn(find.byKey(const Key('team-account-lock'))), isTrue);
- await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
- await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(shortcuts, 0);
- expect(taps, 0);
- expect(dialogTaps, 0);
-
- // A screen reader reads only the lock.
- final read = spoken(tester);
- expect(read.join('\n'), contains('Set up Harness Team on this Mac'));
- expect(read.join('\n'), isNot(contains('Behind')));
- expect(read.join('\n'), isNot(contains('In a dialog')));
- semantics.dispose();
-
- // Set up: the app is as it was, its dialogs still open over it.
- await app.teamAccountMade();
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await tester.tap(find.byKey(const Key('late-dialog-button')));
- expect(dialogTaps, 1);
- },
- );
-
- testWidgets('there is no way to close it', (tester) async {
- await window(tester, app);
- await lock(tester);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await tester.tapAt(const Offset(4, 4));
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- for (final label in ['Cancel', 'Not now', 'Close', 'OK']) {
- expect(find.text(label), findsNothing, reason: label);
- }
- expect(find.byKey(const Key('team-account-lock-remove')), findsNothing);
- expect(
- find.textContaining('This Mac joined a Swarm, so it needs Harness Team'),
- findsOneWidget,
- );
- });
-
- testWidgets('Continue starts setup, and success opens the app', (
- tester,
- ) async {
- daemon.statuses
- ..clear()
- ..addAll([
- {'ok': true, 'state': 'running'},
- {'ok': true, 'state': 'exists'},
- ]);
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- expect(daemon.asked, ['teamSetupCheck', 'teamSetup']);
- expect(
- outcome(tester),
- 'macOS is asking for your password in a window titled “osascript”. '
- 'After that, setup goes on in the background and you can keep working.',
- );
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
- await tester.pump(const Duration(seconds: 2));
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- expect(app.teamSetupLocked, isFalse);
- await tester.tap(find.byKey(const Key('behind-button')));
- expect(taps, 1);
- });
-
- testWidgets('a Mac with the account already opens the app at Continue', (
- tester,
- ) async {
- daemon.run = {'ok': true, 'state': 'exists'};
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- });
-
- testWidgets('a wrong password says so, and Try again asks again', (
- tester,
- ) async {
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'failed', 'detail': _wrongPassword});
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- expect(outcome(tester), 'macOS did not accept that password. Try again.');
- expect(find.byKey(const Key('team-account-lock-remove')), findsNothing);
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'running'});
- await tester.tap(find.byKey(const Key('team-account-lock-retry')));
- await tester.pump();
- expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(2));
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
- });
-
- testWidgets('another failure says the daemon\'s sentence, with Try again', (
- tester,
- ) async {
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'failed', 'detail': 'dscl exited 64.'});
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- expect(outcome(tester), 'Setup did not finish: dscl exited 64.');
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- });
-
- testWidgets(
- 'a closed password window offers Try again and, for a Mac without an administrator, the way out',
- (tester) async {
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'declined'});
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- expect(
- outcome(tester),
- 'The password window was closed before setup finished.',
- );
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- expect(
- find.text(
- 'No administrator password for this Mac? Remove it from the Swarm. '
- 'You can add it again from Machines.',
- ),
- findsOneWidget,
- );
- expect(find.text('Remove this Mac from the Swarm'), findsOneWidget);
- },
- );
-
- testWidgets(
- 'where setup can never finish, it says why and offers only the way out',
- (tester) async {
- daemon.run = {'error': 'INVALID_REQUEST'};
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump();
- expect(
- outcome(tester),
- 'This Mac\'s Harness is too old to set it up from here. Update Harness, '
- 'or run harness team setup in Terminal.',
- );
- expect(find.byKey(const Key('team-account-lock-retry')), findsNothing);
- expect(find.byKey(const Key('team-account-lock-remove')), findsOneWidget);
- },
- );
-
- // Scholes, 2026-11-04: a new member typed his password and the lock sat on
- // its spinner with nothing to press. The daemon had stopped answering
- // `running` (the setup ended with no account and nothing remembered, or the
- // daemon restarted), and the lock read that `none` as "still waiting".
- testWidgets(
- 'a setup that stops with nothing to say ends the wait at once, with Try again',
- (tester) async {
- daemon.statuses
- ..clear()
- ..addAll([
- {'ok': true, 'state': 'running'},
- {'ok': true, 'state': 'none'},
- ]);
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
- await tester.pump(const Duration(seconds: 2));
- expect(
- outcome(tester),
- 'Setup stopped before the Harness Team account was made. Try again.',
- );
- expect(find.byType(CircularProgressIndicator), findsNothing);
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- // Nothing is read again once it has ended.
- final reads = daemon.asked.where((a) => a == 'teamSetupStatus').length;
- await tester.pump(const Duration(seconds: 10));
- expect(
- daemon.asked.where((a) => a == 'teamSetupStatus'),
- hasLength(reads),
- );
- },
- );
-
- testWidgets(
- 'while it waits, Try again and Remove are there, and the waiting text stays',
- (tester) async {
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- expect(
- outcome(tester),
- 'macOS is asking for your password in a window titled “osascript”. '
- 'After that, setup goes on in the background and you can keep working.',
- );
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- expect(find.text('Remove this Mac from the Swarm'), findsOneWidget);
-
- // Still running: Try again reads the status and starts nothing.
- await tester.tap(find.byKey(const Key('team-account-lock-retry')));
- await tester.pump();
- await tester.pump();
- expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(1));
- expect(daemon.asked.last, 'teamSetupStatus');
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
-
- // Remove asks first; Back returns to the wait.
- await tester.tap(find.byKey(const Key('team-account-lock-remove')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 6));
- await tester.pump();
- expect(
- find.byKey(const Key('team-account-lock-confirm')),
- findsOneWidget,
- );
- await tester.tap(find.byKey(const Key('team-account-lock-remove-back')));
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock-confirm')), findsNothing);
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
-
- // No setup runs any more: Try again starts one.
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'none'});
- await tester.tap(find.byKey(const Key('team-account-lock-retry')));
- await tester.pump();
- await tester.pump();
- expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(2));
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
- },
- );
-
- // Scholes, 2026-11-04: the new member's setup did finish, after about 7
- // minutes on a screen that showed no progress. While the password is asked
- // it says how long it has waited; past it, the lock steps aside and this
- // Mac's row says the step and the time left (#3169).
- testWidgets(
- 'while it waits for the password it says how long, and past it the lock steps aside',
- (tester) async {
- daemon.statuses
- ..clear()
- ..addAll([
- {
- 'ok': true,
- 'state': 'running',
- 'step': 'password',
- 'elapsedMs': 1500,
- },
- {
- 'ok': true,
- 'state': 'running',
- 'step': 'engines',
- 'elapsedMs': 125000,
- },
- ]);
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- expect(
- outcome(tester),
- 'macOS is asking for your password in a window titled “osascript”. '
- 'After that, setup goes on in the background and you can keep working.',
- );
- expect(find.text('1 s so far.'), findsOneWidget);
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- await tester.pump(const Duration(seconds: 2));
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- expect(app.teamSetupLocked, isTrue);
- expect(
- TeamSetupWatch.of(app)!.line,
- 'Harness Team: setting up · step 2 of 4 · about 4 min left',
- );
- },
- );
-
- testWidgets(
- 'Try again while it waits opens the app once the account is made',
- (tester) async {
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'exists'});
- await tester.tap(find.byKey(const Key('team-account-lock-retry')));
- await tester.pump();
- await tester.pump();
- expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(1));
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- },
- );
-
- testWidgets('Harness unreachable says so, with Try again', (tester) async {
- daemon.run = {'error': 'SERVICE_UNAVAILABLE'};
- await window(tester, app);
- await lock(tester);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock-retry')), findsOneWidget);
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- });
-
- testWidgets('Remove this Mac from the Swarm removes it and opens the app', (
- tester,
- ) async {
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- // The Swarm lists this Mac, as the join added it.
- f.connection.server.state['machines'] = [
- {'machineId': 'm', 'name': 'Test host', 'contributorId': 'owner'},
- ];
- f.connection.teamCheck = {'state': 'wanted'};
- f.connection.teamRun = {'state': 'unsupported'};
- await f.app.offerTeamAccount('join', tabId: tabId);
- await window(tester, f.app);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pumpAndSettle();
- expect(
- outcome(tester),
- 'Harness Team cannot be set up on this Mac right now.',
- );
- List<Object?> removals() => [
- for (final p in f.connection.server.posts)
- if ((p['command'] as Map?)?['type'] == 'machine.remove') p['command'],
- ];
-
- // Security review of #2779: removing deletes data. Nothing has focus on
- // Remove, so Enter does nothing, and one press only asks, naming the
- // Swarm.
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.sendKeyEvent(LogicalKeyboardKey.space);
- await tester.pumpAndSettle();
- expect(removals(), isEmpty);
- await tester.tap(find.byKey(const Key('team-account-lock-remove')));
- await tester.pumpAndSettle();
- expect(removals(), isEmpty);
- expect(
- tester
- .widget<Text>(find.byKey(const Key('team-account-lock-confirm')))
- .data,
- 'Remove this Mac from Pilot? Its agents there stop, and teammates\' '
- 'work no longer runs on it. You can add it again from Machines.',
- );
- // Back asks nothing, and is where focus waits: Enter there removes nothing.
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(removals(), isEmpty);
- expect(find.byKey(const Key('team-account-lock-confirm')), findsNothing);
- expect(find.byKey(const Key('team-account-lock-remove')), findsOneWidget);
-
- await tester.tap(find.byKey(const Key('team-account-lock-remove')));
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('team-account-lock-remove-confirm')));
- await tester.pumpAndSettle();
- expect(removals(), [
- {'type': 'machine.remove', 'machineId': 'm'},
- ]);
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await tester.pumpWidget(const SizedBox());
- f.app.superTabs.dispose();
- f.dispose();
- await tester.pump();
- });
-
- testWidgets('a removal the Swarm refuses says why, and the lock stays', (
- tester,
- ) async {
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- // The Swarm lists this Mac, as the join added it.
- f.connection.server.state['machines'] = [
- {'machineId': 'm', 'name': 'Test host', 'contributorId': 'owner'},
- ];
- f.connection.teamCheck = {'state': 'wanted'};
- f.connection.teamRun = {'state': 'unsupported'};
- await f.app.offerTeamAccount('join', tabId: tabId);
- f.connection.server.refuse = {
- 'code': 'FORBIDDEN',
- 'message': 'Only the Swarm owner can do that.',
- };
- await window(tester, f.app);
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('team-account-lock-remove')));
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('team-account-lock-remove-confirm')));
- await tester.pumpAndSettle();
- expect(find.text('Only the Swarm owner can do that.'), findsOneWidget);
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- await tester.pumpWidget(const SizedBox());
- f.app.superTabs.dispose();
- f.dispose();
- await tester.pump();
- });
-
- testWidgets(
- 'the app\'s own window is held, its screen still mounted under it',
- (tester) async {
- final own = AppNotifier(
- config: AppConfig.dev,
- authSession: AuthSession(),
- configStore: null,
- cliLogin: _FakeCli(),
- connectionForTest: (_) => daemon,
- );
- addTearDown(own.dispose);
- const machine = Machine(
- machineId: 'm',
- authMode: MachineAuthMode.remote,
- name: 'Test host',
- );
- own.machines = [machine];
- own.machineStates['m'] = MachineState(machine)
- ..localOnly = true
- ..nodeOnline = true
- ..connectionStatus = ConnectionStatus.connected;
- own.teamAccountHereForTest = true;
- own.status = AppStatus.authenticated;
- own.currentUser = const CurrentUserProfile(
- id: 'owner',
- email: '[email protected]',
- );
- await tester.pumpWidget(
- ProviderScope(
- overrides: [appStateProvider.overrideWithValue(own)],
- child: HarnessApp(
- authenticatedScreen: (_) => const SizedBox(key: Key('screen')),
- ),
- ),
- );
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await own.offerTeamAccount('join', tabId: 'tab-1');
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- expect(find.byKey(const Key('screen')), findsOneWidget);
-
- // Review of #2779: the macOS app menu's rows (Settings, Check for
- // Updates, Keyboard Shortcuts…) arrive over a channel, not by focus.
- Future<void> appMenu(String action) async {
- // Not awaited: the action ends when what it opened is closed.
- tester.binding.defaultBinaryMessenger.handlePlatformMessage(
- 'harness/app_menu',
- const StandardMethodCodec().encodeMethodCall(MethodCall(action)),
- (_) {},
- );
- await tester.pump();
- await tester.pump();
- }
-
- await appMenu('settings');
- expect(find.byType(SettingsScreen), findsNothing);
- await own.teamAccountMade();
- await tester.pump();
- await appMenu('settings');
- expect(find.byType(SettingsScreen), findsOneWidget);
- // Settings' own timers end with it.
- await tester.pumpWidget(const SizedBox());
- await tester.pump(const Duration(seconds: 5));
- },
- );
-
- // The window as people see it, over a stand-in for the app behind it.
- final scenes = <(String, Future<void> Function(WidgetTester))>[
- ('1-on-join', (_) async {}),
- (
- '2-macos-asking',
- (tester) async {
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- // Far enough into the spinner's turn that its arc shows.
- await tester.pump(const Duration(milliseconds: 600));
- },
- ),
- (
- '2b-installing-engines',
- (tester) async {
- daemon.statuses
- ..clear()
- ..add({
- 'ok': true,
- 'state': 'running',
- 'step': 'engines',
- 'elapsedMs': 125000,
- });
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- await tester.pump(const Duration(milliseconds: 600));
- },
- ),
- (
- '3-wrong-password',
- (tester) async {
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'failed', 'detail': _wrongPassword});
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- },
- ),
- (
- '4-password-window-closed',
- (tester) async {
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'declined'});
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- },
- ),
- (
- '5-cannot-set-up-here',
- (tester) async {
- daemon.run = {'error': 'INVALID_REQUEST'};
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump();
- },
- ),
- (
- '6-remove-asks-first',
- (tester) async {
- daemon.run = {'error': 'INVALID_REQUEST'};
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('team-account-lock-remove')));
- await tester.pump();
- // No Swarm answers here: its name is given up on, and it still asks.
- await tester.pump(const Duration(seconds: 6));
- await tester.pump();
- expect(
- find.byKey(const Key('team-account-lock-confirm')),
- findsOneWidget,
- );
- },
- ),
- ];
- for (final brightness in Brightness.values) {
- for (final (name, arrange) in scenes) {
- testWidgets('picture $name (${brightness.name})', (tester) async {
- debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
- await tester.binding.setSurfaceSize(const Size(1000, 700));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- builder: (context, child) => TeamAccountSetupLock(
- app: app,
- operatingSystem: 'macos',
- child: child!,
- ),
- home: Scaffold(
- body: Padding(
- padding: const EdgeInsets.all(24),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text('Pilot', style: grid.AppType.title()),
- const SizedBox(height: 12),
- for (final line in [
- 'Lead: the plan for the release is in the thread.',
- 'Ken: Looks good, go ahead.',
- 'Builder: PR #2779 is ready for review.',
- ])
- Padding(
- padding: const EdgeInsets.only(bottom: 8),
- child: Text(line, style: grid.AppType.body()),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- await lock(tester);
- await arrange(tester);
- await captureWindow(tester, shots, '$name-${brightness.name}');
- await tester.pumpWidget(const SizedBox());
- debugDefaultTargetPlatformOverride = null;
- }, skip: shots == null);
- }
- }
-
- // The task's Done when, end to end in one window (River, 11-03: the Tester
- // may not run the real setup on a shared Mac, so this walk is the check):
- // the Machines view as the app shows it, this Mac joining, the window over
- // it at once, nothing behind it reachable, a wrong password, Try again, the
- // right one, and the Mac set up in Machines.
- for (final brightness in Brightness.values) {
- testWidgets(
- 'join → window at once → wrong password → Try again → set up, and Machines says so (${brightness.name})',
- (tester) async {
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);
- Map<String, dynamic> pool(
- String id, {
- String? host,
- Map<String, dynamic>? teamWork,
- }) => {
- 'machineId': id,
- 'name': host == null ? 'Test host' : 'Test host · Team',
- 'contributorId': 'owner',
- 'scope': 'swarm',
- 'cwd': '/swarm',
- 'engines': ['codex'],
- 'maxAgents': 4,
- 'paused': false,
- 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
- 'hostMachineId': ?host,
- 'teamWork': teamWork ?? {'allowed': true},
- };
- const notSetUp = {
- 'allowed': false,
- 'code': 'TEAM_ACCOUNT_REQUIRED',
- 'reason': 'Test host has no Harness Team account yet.',
- };
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- // A Swarm with a teammate, whose agents would run on this Mac.
- (f.connection.server.state['people'] as List).add({
- 'id': 'peer',
- 'email': '[email protected]',
- 'role': 'collaborator',
- });
- f.connection.server.state['machines'] = [pool('m', teamWork: notSetUp)];
- f.connection.teamCheck = {'state': 'wanted'};
- final c = await f.app.superTabs.open(tabId);
- await c.refresh();
- var added = 0;
- await tester.binding.setSurfaceSize(const Size(1000, 700));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- Future<void> openMachines() async {
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- builder: (context, child) => TeamAccountSetupLock(
- app: f.app,
- operatingSystem: 'macos',
- child: child!,
- ),
- home: Scaffold(
- body: SuperTabMachines(
- controller: c,
- onAddAgent: (_) => added++,
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- }
-
- await openMachines();
- final problem = find.byKey(const ValueKey('super-machine-problem-m'));
- expect(
- tester.widget<Text>(problem).data,
- "Teammates' agents paused: not set up",
- );
- await captureWindow(
- tester,
- shots,
- 'walk-1-machines-not-set-up-${brightness.name}',
- );
-
- // Joined: the window is there at once, in the same frame.
- await f.app.offerTeamAccount('join', tabId: tabId);
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- await captureWindow(tester, shots, 'walk-2-joined-${brightness.name}');
- final lock = find.byKey(const Key('team-account-lock'));
- bool inLock() {
- final focused = FocusManager.instance.primaryFocus?.context;
- return focused != null &&
- lock.evaluate().any(
- (e) =>
- e == focused ||
- (focused as Element).debugGetDiagnosticChain().contains(e),
- );
- }
-
- // Nothing behind it: Tab, arrows and Escape stay in the window, a click
- // on the machine row does nothing.
- for (final key in [
- LogicalKeyboardKey.tab,
- LogicalKeyboardKey.arrowDown,
- LogicalKeyboardKey.arrowUp,
- LogicalKeyboardKey.arrowLeft,
- LogicalKeyboardKey.arrowRight,
- LogicalKeyboardKey.tab,
- LogicalKeyboardKey.escape,
- ]) {
- await tester.sendKeyEvent(key);
- await tester.pump();
- expect(inLock(), isTrue, reason: '$key');
- expect(lock, findsOneWidget, reason: '$key');
- }
- final expanded = c.isMachineExpanded('m');
- await tester.tap(
- find.byKey(const ValueKey('super-machine-m')),
- warnIfMissed: false,
- );
- await tester.pump();
- expect(c.isMachineExpanded('m'), expanded);
- expect(added, 0);
-
- // A wrong password: said, and Try again asks again.
- f.connection.teamSetup = {'state': 'running'};
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- f.connection.teamSetup = {'state': 'failed', 'detail': _wrongPassword};
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- expect(
- outcome(tester),
- 'macOS did not accept that password. Try again.',
- );
- await captureWindow(
- tester,
- shots,
- 'walk-3-wrong-password-${brightness.name}',
- );
-
- // The right one: setup finishes, and the window goes.
- f.connection.teamSetup = {'state': 'running'};
- await tester.tap(find.byKey(const Key('team-account-lock-retry')));
- await tester.pump();
- expect(find.byType(CircularProgressIndicator), findsOneWidget);
- f.connection.teamSetup = {'state': 'exists'};
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- expect(f.app.teamSetupLocked, isFalse);
-
- // Its Team account reports in, and Machines shows the Mac set up.
- f.connection.server.state['machines'] = [
- pool('m', teamWork: notSetUp),
- pool('m-team', host: 'm'),
- ];
- await c.refresh();
- // Machines, opened again: the Mac's row no longer says it is paused.
- await tester.pumpWidget(const SizedBox());
- await openMachines();
- expect(problem, findsNothing);
- await captureWindow(
- tester,
- shots,
- 'walk-4-machines-set-up-${brightness.name}',
- );
-
- await tester.pumpWidget(const SizedBox());
- await c.flush();
- f.app.superTabs.dispose();
- f.dispose();
- await tester.pump();
- },
- );
- }
-
- // Diego, 11-03: saving a machine's settings locked the whole app behind the
- // Team account setup, in the Personal Swarm too and after an earlier Not
- // now, and a refused Remove left no way out.
- group('settings and Personal never lock the app', () {
- /// The daemon's setup checks asked with [reason].
- List<Map<String, dynamic>> checks(SuperTabLaunchFixture f, String reason) =>
- [
- for (final (type, payload) in f.connection.calls)
- if (type == 'super_tabs' &&
- payload['action'] == 'teamSetupCheck' &&
- payload['reason'] == reason)
- payload,
- ];
-
- List<Map<String, dynamic>> contributions(SuperTabLaunchFixture f) => [
- for (final post in f.connection.server.posts)
- if ((post['command'] as Map?)?['type'] == 'machine.contribute')
- Map<String, dynamic>.from(post['command'] as Map),
- ];
-
- /// This Mac, already in the fixture's Swarm, as its owner contributed it.
- SuperTabLaunchFixture contributed({required String check}) {
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- for (final state in f.app.machineStates.values) {
- state.localOnly = true;
- }
- f.connection.maxAvailableAgents = 16;
- f.connection.teamCheck = {'state': check};
- f.connection.server.state['machines'] = [
- {'machineId': 'm', 'contributorId': 'owner', 'maxAgents': 16},
- ];
- return f;
- }
-
- /// The fixture's Swarm made the person's Personal one, as
- /// super_tab_personal_projects_test.dart makes it.
- Future<SuperTabController> personal(SuperTabLaunchFixture f) async {
- f.connection.server.state
- ..['name'] = 'Personal'
- ..['ownerId'] = 'owner'
- ..['people'] = [
- {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
- ];
- await f.app.superTabs.storage.write('super_tab.personal.owner', tabId);
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');
- PersonalSwarm.of(f.app).id;
- for (var i = 0; i < 20; i++) {
- await Future<void>.microtask(() {});
- }
- expect(PersonalSwarm.of(f.app).id, tabId);
- final c = await f.app.superTabs.open(tabId);
- await c.refresh();
- return c;
- }
-
- /// Manage > Machines > this Mac > Configure, one fewer agent, Save.
- Future<void> saveSettings(
- WidgetTester tester,
- SuperTabLaunchFixture f,
- SuperTabController c,
- ) async {
- await tester.pumpWidget(
- MaterialApp(
- builder: (context, child) => TeamAccountSetupLock(
- app: f.app,
- operatingSystem: 'macos',
- child: child!,
- ),
- home: Scaffold(
- body: SizedBox(
- width: 300,
- height: 400,
- child: SuperTabMachines(
- controller: c,
- app: f.app,
- onAddAgent: (_) {},
- readLocal: (_) async => const MachineResources(
- memoryTotalBytes: 32 * 1024 * 1024 * 1024,
- memoryUsedBytes: 31 * 1024 * 1024 * 1024,
- ),
- ),
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- await tester.tap(
- find.byKey(const ValueKey('super-machine-m')),
- buttons: kSecondaryMouseButton,
- );
- await tester.pumpAndSettle();
- await tester.tap(find.text('Details').last);
- await tester.pumpAndSettle();
- await tester.tap(find.widgetWithText(TextButton, 'Configure'));
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('agent-limit-fewer')));
- await tester.pumpAndSettle();
- await tester.tap(find.widgetWithText(FilledButton, 'Save'));
- // Preparation is ready from its second read, a second apart.
- for (var i = 0; i < 3; i++) {
- await tester.pump(const Duration(seconds: 1));
- await tester.pumpAndSettle();
- }
- }
-
- Future<void> close(
- WidgetTester tester,
- SuperTabLaunchFixture f,
- SuperTabController c,
- ) async {
- await tester.pumpWidget(const SizedBox());
- await c.flush();
- f.app.superTabs.dispose();
- f.dispose();
- await tester.pump();
- }
-
- testWidgets(
- 'saving settings after an earlier Not now sends the change and locks nothing',
- (tester) async {
- final f = contributed(check: 'declined');
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- final c = await f.app.superTabs.open(tabId);
- await c.refresh();
- await saveSettings(tester, f, c);
-
- expect(contributions(f).single['maxAgents'], 7);
- expect(checks(f, 'contribute'), isEmpty);
- expect(f.app.teamSetupLocked, isFalse);
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await close(tester, f, c);
- },
- );
-
- testWidgets(
- 'saving settings in the Personal Swarm with the account wanted locks nothing',
- (tester) async {
- final f = contributed(check: 'wanted');
- final c = await personal(f);
- await saveSettings(tester, f, c);
-
- expect(contributions(f).single['maxAgents'], 7);
- expect(checks(f, 'contribute'), isEmpty);
- expect(f.app.teamSetupLocked, isFalse);
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await close(tester, f, c);
- },
- );
-
- testWidgets(
- 'adding this Mac to the Personal Swarm with the account wanted asks nothing',
- (tester) async {
- final f = contributed(check: 'wanted');
- f.connection.server.state['machines'] = <Map<String, dynamic>>[];
- final c = await personal(f);
- await tester.pumpWidget(const SizedBox());
- // The Add machine form's own call, which offers the account by
- // default.
- String? added;
- unawaited(
- contributeComputer(
- c,
- f.app,
- 'm',
- setupId: 'setup-1',
- alive: () => true,
- readResources: (_) async => null,
- ).then((id) => added = id),
- );
- for (var i = 0; i < 4; i++) {
- await tester.pump(const Duration(seconds: 1));
- }
- expect(added, 'm');
- expect(contributions(f), hasLength(1));
- expect(checks(f, 'contribute'), isEmpty);
- expect(f.app.teamSetupLocked, isFalse);
- await close(tester, f, c);
- },
- );
-
- testWidgets(
- 'a refused removal offers Not now, which records it and opens the app',
- (tester) async {
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- f.connection.server.state['machines'] = [
- {'machineId': 'm', 'name': 'Test host', 'contributorId': 'owner'},
- ];
- f.connection.teamCheck = {'state': 'wanted'};
- f.connection.teamRun = {'state': 'unsupported'};
- await f.app.offerTeamAccount('join', tabId: tabId);
- // The Mac runs a project's PM: the Swarm keeps it.
- f.connection.server.refuse = {
- 'code': 'LEAD_PROTECTED',
- 'message': 'This machine runs the PM of a project.',
- };
- await window(tester, f.app);
- // No way out before Remove was tried.
- expect(
- find.byKey(const Key('team-account-lock-not-now')),
- findsNothing,
- );
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pumpAndSettle();
- expect(
- find.byKey(const Key('team-account-lock-not-now')),
- findsNothing,
- );
- await tester.tap(find.byKey(const Key('team-account-lock-remove')));
- await tester.pumpAndSettle();
- await tester.tap(
- find.byKey(const Key('team-account-lock-remove-confirm')),
- );
- await tester.pumpAndSettle();
- expect(
- find.text('This machine runs the PM of a project.'),
- findsOneWidget,
- );
- // It no longer asks for the Remove that was just refused.
- expect(
- find.textContaining('remove this Mac from the Swarm'),
- findsNothing,
- );
- expect(
- find.byKey(const Key('team-account-lock-not-now-why')),
- findsOneWidget,
- );
- if (shots != null) {
- debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
- await tester.binding.setSurfaceSize(const Size(1000, 700));
- await tester.pumpAndSettle();
- await captureWindow(tester, shots, '7-remove-refused-not-now');
- await tester.binding.setSurfaceSize(null);
- debugDefaultTargetPlatformOverride = null;
- await tester.pumpAndSettle();
- }
-
- await tester.tap(find.byKey(const Key('team-account-lock-not-now')));
- await tester.pumpAndSettle();
- expect(
- [
- for (final (type, payload) in f.connection.calls)
- if (type == 'super_tabs' &&
- payload['action'] == 'teamSetupDecline')
- payload['action'],
- ],
- ['teamSetupDecline'],
- );
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- expect(f.app.teamSetupLocked, isFalse);
- await tester.pumpWidget(const SizedBox());
- f.app.superTabs.dispose();
- f.dispose();
- await tester.pump();
- },
- );
- });
-
- // A contribution locks only while the account is to be made now; a join
- // after an earlier cancel or failure still does (it is a new Swarm).
- for (final (state, locks) in [
- ('wanted', true),
- ('running', true),
- ('declined', false),
- ('waiting', false),
- ('no-prompt', false),
- ]) {
- test(
- 'a contribution answered $state ${locks ? 'locks' : 'does not lock'}',
- () async {
- daemon.check = {'ok': true, 'state': state};
- await app.offerTeamAccount('contribute', tabId: 'tab-1');
- expect(app.teamSetupLocked, locks);
- },
- );
- }
-
- for (final state in [
- 'wanted',
- 'declined',
- 'waiting',
- 'running',
- 'no-prompt',
- ]) {
- test('a join answered $state locks', () async {
- daemon.check = {'ok': true, 'state': state};
- await app.offerTeamAccount('join', tabId: 'tab-1');
- expect(app.teamSetupLocked, isTrue);
- });
- }
-}
diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dart
index 7079ef4e3..d84909d4b 100644
--- a/desktop/test/team_account_offer_test.dart
+++ b/desktop/test/team_account_offer_test.dart
@@ -1,29 +1,26 @@
+// Swarm v3 has no Harness Team accounts (anh Dee, 2026-11-07; #4120 sends no
+// new work to one): Desktop never offers to set one up, never holds the app
+// for one, and shows no Set up for one (#4221). Its daemon no longer answers
+// the `teamSetup*` actions, so asking them only fails.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
-import 'package:harness/state/app_state.dart';
-import 'package:harness/super_tabs/machines.dart'
- show superTabTeamSetupAction, superTabTeamSetupLine;
-import 'package:harness/super_tabs/team_account_setup.dart';
+import 'package:harness/super_tabs/machines.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
import 'support/rename_connection.dart';
+import 'support/super_tab_fixture.dart';
import 'swarm_state_test.dart' show MemoryStore, createApp;
-/// Records what this Mac's daemon is asked; no socket is opened.
+/// Records every Team account setup action this computer's daemon is asked;
+/// no socket is opened.
class _Daemon extends RenameConnection {
- final asked = <Map<String, dynamic>>[];
- Map<String, dynamic> answer = {'ok': true, 'state': 'wanted'};
-
- /// Answers in turn before [answer]; a Completer's future is awaited.
- final queued = <Object>[];
-
- /// What `teamSetupStatus` answers: what this Mac's daemon remembers of the
- /// account's setup.
- Map<String, dynamic> status = {'ok': true, 'state': 'none'};
+ final asked = <String>[];
@override
Future<Map<String, dynamic>> request(
@@ -31,795 +28,184 @@ class _Daemon extends RenameConnection {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
}) {
- if (type == 'super_tabs' &&
- '${payload['action']}'.startsWith('teamSetup')) {
- asked.add(Map.of(payload));
- if (payload['action'] == 'teamSetupStatus') return Future.value(status);
- if (queued.isNotEmpty) {
- final next = queued.removeAt(0);
- return next is Completer<Map<String, dynamic>>
- ? next.future
- : Future.value(next as Map<String, dynamic>);
- }
- return Future.value(answer);
+ final action = '${payload['action']}';
+ if (type == 'super_tabs' && action.startsWith('teamSetup')) {
+ asked.add(action);
+ return Future.value({'ok': true, 'state': 'wanted'});
}
return super.request(type, payload: payload, timeout: timeout);
}
}
-/// Waits until [ok] holds, failing after two seconds.
-Future<void> until(bool Function() ok) async {
- final deadline = DateTime.now().add(const Duration(seconds: 2));
- while (!ok()) {
- if (DateTime.now().isAfter(deadline)) fail('timed out waiting');
- await Future<void>.delayed(const Duration(milliseconds: 1));
- }
+/// This computer's daemon answers its status at once: nothing waits on a
+/// real probe.
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+
+ @override
+ Future<LocalCliProbe> probe({String? expectedComputerId}) async =>
+ const LocalCliProbe.down('test');
}
-const startCheck = {'action': 'teamSetupCheck', 'reason': 'startup'};
+bool _teamSetup(Map<String, dynamic> payload) =>
+ '${payload['action']}'.startsWith('teamSetup');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
- late _Daemon daemon;
- late AppNotifier app;
- /// Which daemon process answers this Mac: a new one after a restart, null
- /// when its status could not be read.
- String? running = 'pid-1';
- AppNotifier make(_Daemon daemon, {MemoryStore? store}) {
+ test('at startup this computer\'s daemon is asked nothing of a Team account, '
+ 'though a lock was saved before', () async {
+ final daemon = _Daemon();
+ // A lock a Desktop from before saved, for a Swarm this Mac joined.
+ final store = MemoryStore()
+ ..values['team_setup_lock.owner'] = jsonEncode(['tab-1']);
final app = createApp(
connectionForTest: (_) => daemon,
connected: true,
store: store,
+ localCliDiscovery: _Discovery(),
);
+ addTearDown(app.dispose);
app.currentUser = const CurrentUserProfile(
id: 'owner',
);
app.machineStates['m']!.localOnly = true;
app.teamAccountHereForTest = true;
- app.daemonIdentityForTest = () async => running;
- app.teamOfferRetryForTest = const Duration(milliseconds: 1);
- return app;
- }
-
- setUp(() {
- running = 'pid-1';
- daemon = _Daemon();
- app = make(daemon);
- });
- tearDown(() => app.dispose());
-
- test('asks this Mac\'s own daemon whether it is wanted, for the Swarm joined or added to', () async {
- final explained = <String>[];
- final listening = app.teamSetupAsks.listen(explained.add);
- await app.offerTeamAccount('join', tabId: 'tab-1');
- daemon.answer = {'ok': true, 'state': 'declined'};
- await app.offerTeamAccount('contribute', tabId: 'tab-2');
- await pumpEventQueue();
- expect(daemon.asked, [
- {'action': 'teamSetupCheck', 'reason': 'join', 'tabId': 'tab-1'},
- {'action': 'teamSetupCheck', 'reason': 'contribute', 'tabId': 'tab-2'},
- ]);
- // A join or a contribution locks the app instead (team_account_setup.dart
- // TeamAccountSetupLock): nothing is explained behind it.
- expect(explained, isEmpty);
- expect(app.teamSetupLocked, isTrue);
- await listening.cancel();
- });
-
- // Scholes 11-03: a Mac joined a Swarm and stayed "not set up" until someone
- // found its row in Machines. The window now opens on join and stays.
- test('a join locks the app once, however often it is asked, until the account exists', () async {
- var changes = 0;
- app.addListener(() => changes++);
- expect(app.teamSetupLocked, isFalse);
- await app.offerTeamAccount('join', tabId: 'tab-1');
- expect(app.teamSetupLocked, isTrue);
- final first = changes;
- await app.offerTeamAccount('join', tabId: 'tab-1');
- expect(changes, first, reason: 'the same Swarm again changes nothing');
- await app.offerTeamAccount('join', tabId: 'tab-2');
- expect(app.teamSetupLocked, isTrue);
- await app.teamAccountMade();
- expect(app.teamSetupLocked, isFalse);
- });
-
- test('a join on a Mac that has the account, or whose daemon cannot say, does not lock', () async {
- for (final answer in [
- {'ok': true, 'state': 'exists'},
- {'ok': true, 'state': 'unsupported'},
- {'ok': true, 'state': 'dedicated'},
- {'error': 'UNKNOWN_ACTION'},
- ]) {
- daemon.answer = answer;
- await app.offerTeamAccount('join', tabId: 'tab-1');
- expect(app.teamSetupLocked, isFalse, reason: '$answer');
- }
- });
-
- // A cancel remembered from before (the old "Not now", or macOS's prompt
- // closed) kept every later join from asking.
- test(
- 'a cancel or a failure remembered from before still locks a new join',
- () async {
- for (final state in ['declined', 'waiting', 'running', 'no-prompt']) {
- daemon.answer = {'ok': true, 'state': state};
- await app.offerTeamAccount('join', tabId: 'tab-1');
- expect(app.teamSetupLocked, isTrue, reason: state);
- await app.teamAccountMade();
- }
- },
- );
-
- test(
- 'the start check never locks: only a join or a contribution does',
- () async {
- await app.offerTeamAccount('startup');
- expect(app.teamSetupLocked, isFalse);
- },
- );
-
- test('the lock comes back after a restart, until the account exists', () async {
- final store = MemoryStore();
- final first = make(daemon, store: store);
- await first.offerTeamAccount('join', tabId: 'tab-1');
- expect(first.teamSetupLocked, isTrue);
- first.dispose();
-
- // Quit and opened again, the account still missing: locked as it connects.
- final again = _Daemon()..answer = {'ok': true, 'state': 'not-shared'};
- final second = make(again, store: store);
- addTearDown(second.dispose);
- expect(second.teamSetupLocked, isFalse);
- second.onMachineConnectedForTest('m');
- await until(() => second.teamSetupLocked);
-
- // Set up meanwhile (in Terminal): the next start is not locked, and
- // forgets it.
- final made = _Daemon()
- ..answer = {'ok': true, 'state': 'exists'}
- ..status = {'ok': true, 'state': 'exists'};
- final third = make(made, store: store);
- addTearDown(third.dispose);
- third.onMachineConnectedForTest('m');
- await until(() => made.asked.any((a) => a['action'] == 'teamSetupStatus'));
- await pumpEventQueue();
- expect(third.teamSetupLocked, isFalse);
- expect(
- store.values.keys.where((k) => k.startsWith('team_setup_lock')),
- isEmpty,
- );
- });
-
- test(
- 'another account signed in on this computer is not held by it',
- () async {
- await app.offerTeamAccount('join', tabId: 'tab-1');
- app.currentUser = const CurrentUserProfile(
- id: 'other',
- email: '[email protected]',
- );
- expect(app.teamSetupLocked, isFalse);
- },
- );
-
- test('restarts Team through manual setup without replacing its sign-in', () async {
- daemon.answer = {'ok': true, 'state': 'started'};
- expect(await app.setUpTeamAccount(restart: true), 'started');
- expect(daemon.asked, [
- {'action': 'teamSetup', 'reason': 'manual', 'restart': true},
- ]);
- });
-
- test('sets it up when the person asks, and remembers "Not now"', () async {
- daemon.answer = {'ok': true, 'state': 'started'};
- expect(await app.setUpTeamAccount(), 'started');
- await app.declineTeamAccount();
- expect(daemon.asked, [
- {'action': 'teamSetup', 'reason': 'manual'},
- {'action': 'teamSetupDecline'},
- ]);
- expect(app.canSetUpTeamAccount, isTrue);
- app.teamAccountHereForTest = false;
- expect(app.canSetUpTeamAccount, isFalse);
- expect(await app.setUpTeamAccount(), 'unsupported');
- });
-
- test('a daemon too old to set it up from here says so', () async {
- daemon.answer = {'error': 'INVALID_REQUEST'};
- expect(await app.setUpTeamAccount(), 'update');
- });
-
- test('asks nothing where the account cannot be made, or when the only machine here is another one', () async {
- app.teamAccountHereForTest = false;
- await app.offerTeamAccount('join');
- app.teamAccountHereForTest = true;
- app.machineStates['m']!.localOnly = false;
- await app.offerTeamAccount('join');
- expect(daemon.asked, isEmpty);
- });
-
- // Linux and Windows make the same account a Mac does (plans of 2026-10-28;
- // Windows' daemon sets it up behind User Account Control). A phone, a tablet
- // and a browser never do.
- test('the account is offered on a Mac, Linux and Windows, nowhere else', () {
- for (final os in ['macos', 'linux', 'windows']) {
- expect(AppNotifier.teamAccountOn(os), isTrue, reason: os);
- }
- for (final os in ['web', 'ios', 'android', 'fuchsia']) {
- expect(AppNotifier.teamAccountOn(os), isFalse, reason: os);
- }
- });
-
- test(
- 'never for a machine shared with this account, at a join or at start',
- () async {
- final state = app.machineStates['m']!;
- state.machine = Machine(
- machineId: 'm',
- authMode: MachineAuthMode.remote,
- name: 'Dee\'s computer',
- machineShare: const MachineShare(
- ownerName: 'Dee',
- ownerEmail: '[email protected]',
- via: 'email',
- added: true,
- ),
- );
- expect(app.canSetUpTeamAccount, isFalse);
- await app.offerTeamAccount('join');
- app.onMachineConnectedForTest('m');
- await Future<void>.delayed(const Duration(milliseconds: 20));
- expect(daemon.asked, isEmpty);
- },
- );
-
- test('a daemon that refuses or cannot say is left alone', () async {
- daemon.answer = {'error': 'UNKNOWN_ACTION'};
- await app.offerTeamAccount('join');
- expect(daemon.asked, hasLength(1));
- });
-
- test(
- 'checks once for each process of this Mac\'s daemon, as it connects',
- () async {
- app.onMachineConnectedForTest('m');
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.isNotEmpty);
- await pumpEventQueue();
- expect(daemon.asked, [startCheck]);
- },
- );
-
- // Macs already in a Swarm met no join or contribute moment, and the one ask
- // a launch went to whichever daemon answered first: one still starting, or
- // the version from before an update, so nobody saw the prompt (2026-10-27).
- test(
- 'checks again when this Mac\'s daemon has restarted, which decides',
- () async {
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.length == 1);
- await pumpEventQueue();
- // A new daemon process, after an update for instance: asked again.
- running = 'pid-2';
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.length == 2);
- expect(daemon.asked, everyElement(startCheck));
- },
- );
-
- // A start check runs for each daemon process, so a restart while the
- // explanation is still open must not show it a second time.
- test(
- 'explains at start once a launch, though a restarted daemon still wants it',
- () async {
- final explained = <String>[];
- final listening = app.teamSetupAsks.listen(explained.add);
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.length == 1);
- await pumpEventQueue();
- running = 'pid-2';
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.length == 2);
- await pumpEventQueue();
- expect(explained, ['startup']);
- // The person joining is held by the lock instead, never explained again.
- await app.offerTeamAccount('join', tabId: 'tab-1');
- await pumpEventQueue();
- expect(explained, ['startup']);
- expect(app.teamSetupLocked, isTrue);
- await listening.cancel();
- },
- );
-
- test('checks one at a time', () async {
- final pending = Completer<Map<String, dynamic>>();
- daemon.queued.add(pending);
- app.onMachineConnectedForTest('m');
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.isNotEmpty);
- await pumpEventQueue();
- expect(daemon.asked, hasLength(1));
- pending.complete({'ok': true, 'state': 'not-shared'});
- await pumpEventQueue();
- expect(daemon.asked, hasLength(1));
- });
-
- // Review of #1790: every socket reconnect started a fresh budget, so a
- // daemon that could not answer was asked at the reconnect rate for good.
- test('keeps its budget across reconnects to the same daemon, and asks nothing more once it answered', () async {
- daemon.answer = {'error': 'SERVICE_UNAVAILABLE'};
- for (var i = 0; i < 20; i++) {
- app.onMachineConnectedForTest('m');
- await Future<void>.delayed(const Duration(milliseconds: 2));
- }
- await until(() => daemon.asked.length == 5);
- await Future<void>.delayed(const Duration(milliseconds: 30));
- // Five tries for one daemon, however often its socket reconnected.
- expect(daemon.asked, hasLength(5));
- // The same daemon, once it answered, is not asked on a reconnect.
- running = 'pid-2';
- daemon.answer = {'ok': true, 'state': 'not-shared'};
- app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.length == 6);
- for (var i = 0; i < 5; i++) {
- app.onMachineConnectedForTest('m');
- await pumpEventQueue();
- }
- await Future<void>.delayed(const Duration(milliseconds: 20));
- expect(daemon.asked, hasLength(6));
- });
-
- // Re-check of #1790: a status read that timed out has no identity, which
- // counted as a new process, so a daemon whose status read now and then
- // timed out was asked without end.
- test('keeps its budget when the daemon\'s identity cannot be read', () async {
- daemon.answer = {'error': 'SERVICE_UNAVAILABLE'};
- for (var i = 0; i < 20; i++) {
- running = i.isEven ? 'pid-1' : null;
- app.onMachineConnectedForTest('m');
- await Future<void>.delayed(const Duration(milliseconds: 2));
- }
- await until(() => daemon.asked.length == 5);
- await Future<void>.delayed(const Duration(milliseconds: 30));
- // Five tries for the one daemon whose status read timed out in between.
- expect(daemon.asked, hasLength(5));
- // Only a different confirmed process starts over.
- running = 'pid-2';
app.onMachineConnectedForTest('m');
- await until(() => daemon.asked.length == 6);
+ await pumpEventQueue(times: 100);
+ expect(daemon.asked, isEmpty);
});
- test(
- 'checks again, a few times, a daemon that could not answer yet',
- () async {
- daemon.queued.addAll([
- {'error': 'SERVICE_UNAVAILABLE'},
- {'error': 'SERVICE_UNAVAILABLE'},
- ]);
- app.onMachineConnectedForTest('m');
- // Two that could not say, then an answer.
- await until(() => daemon.asked.length == 3);
- await Future<void>.delayed(const Duration(milliseconds: 20));
- expect(daemon.asked, hasLength(3));
- },
- );
-
- // Review of #1790: a request still out at dispose resumed and scheduled a
- // retry on a disposed app.
- test(
- 'schedules nothing after it is disposed, though a request was out',
- () async {
- final own = _Daemon();
- final other = make(own);
- final pending = Completer<Map<String, dynamic>>();
- own.queued.add(pending);
- other.onMachineConnectedForTest('m');
- await until(() => own.asked.isNotEmpty);
- other.dispose();
- pending.complete({'error': 'ACCOUNT_CHANGED'});
- await Future<void>.delayed(const Duration(milliseconds: 30));
- expect(own.asked, hasLength(1));
- },
- );
-
- Future<void> open(
- WidgetTester tester, {
- bool asked = false,
- String operatingSystem = 'macos',
- }) async {
- await tester.pumpWidget(
- MaterialApp(
- home: Builder(
- builder: (context) => TextButton(
- onPressed: () => showTeamAccountSetup(
- context,
- app,
- asked: asked,
- operatingSystem: operatingSystem,
- ),
- child: const Text('open'),
- ),
- ),
- ),
- );
- await tester.tap(find.text('open'));
- await tester.pumpAndSettle();
- }
-
- /// The dialog's title and its three paragraphs, as shown.
- List<String> shown(WidgetTester tester) => [
- for (final text in tester.widgetList<Text>(
- find.descendant(
- of: find.byKey(const Key('team-account-setup')),
- matching: find.byType(Text),
- ),
- ))
- if (!const {'Not now', 'Cancel', 'Continue'}.contains(text.data))
- text.data!,
- ];
-
- /// What the dialog says once Continue was pressed, the daemon answering
- /// [answer].
- Future<String> outcome(
- WidgetTester tester,
- String operatingSystem,
- Map<String, dynamic> answer,
- ) async {
- daemon.answer = answer;
- await open(tester, operatingSystem: operatingSystem);
- await tester.tap(find.byKey(const Key('team-account-setup-continue')));
- await tester.pumpAndSettle();
- final said = tester
- .widget<Text>(find.byKey(const Key('team-account-setup-outcome')))
- .data!;
- await tester.tap(find.byKey(const Key('team-account-setup-done')));
- await tester.pumpAndSettle();
- return said;
- }
-
- const paragraph3 =
- 'Your home folder becomes private to you. Your own agents work as before. '
- 'To remove the account later, run harness team remove.';
- const computerParagraph1 =
- 'Teammates\' agents in your Swarms run on this computer in a separate '
- 'account, Harness Team. They cannot read your files or use your GitHub login. '
- 'They use this computer\'s Claude Code and Codex subscriptions, so nobody signs in again.';
-
testWidgets(
- 'a half-made account: the dialog says what is missing and offers Repair, which runs setup again (#2765)',
+ 'adding this Mac to a Swarm asks its daemon nothing of a Team account',
(tester) async {
- await tester.pumpWidget(
- MaterialApp(
- home: Builder(
- builder: (context) => TextButton(
- onPressed: () => showTeamAccountSetup(
- context,
- app,
- operatingSystem: 'macos',
- missing: 'the team daemon is not running',
- ),
- child: const Text('open'),
- ),
- ),
- ),
- );
- await tester.tap(find.text('open'));
- await tester.pumpAndSettle();
- expect(find.text('Repair Harness Team on this Mac'), findsOneWidget);
+ final f = SuperTabLaunchFixture();
+ f.app.teamAccountHereForTest = true;
+ for (final state in f.app.machineStates.values) {
+ state.localOnly = true;
+ }
+ f.connection.server.state['machines'] = <Map<String, dynamic>>[];
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ String? added;
+ unawaited(
+ contributeComputer(
+ c,
+ f.app,
+ 'm',
+ setupId: 'setup-1',
+ alive: () => true,
+ readResources: (_) async => null,
+ ).then((id) => added = id),
+ );
+ // Preparation is ready from its second read, a second apart.
+ for (var i = 0; i < 4; i++) {
+ await tester.pump(const Duration(seconds: 1));
+ }
+ expect(added, 'm');
expect(
- find.text(
- 'Harness Team is not finished on this Mac: the team daemon is not running. Repair runs its setup again.',
+ f.connection.server.posts.where(
+ (post) => (post['command'] as Map?)?['type'] == 'machine.contribute',
),
- findsOneWidget,
- );
- expect(find.text('Continue'), findsNothing);
- expect(
- find.text('Harness Team is already set up on this Mac.'),
- findsNothing,
- );
- daemon.answer = {'ok': true, 'state': 'started'};
- await tester.tap(find.byKey(const Key('team-account-setup-continue')));
- await tester.pumpAndSettle();
- expect(
- find.byKey(const Key('team-account-setup-outcome')),
- findsOneWidget,
- );
- expect(
- daemon.asked
- .where((p) => p['action'] == 'teamSetup')
- .map((p) => p['reason']),
- ['manual'],
- );
- },
- );
-
- test('the machine row names the missing part and offers Repair (#2765)', () {
- expect(
- superTabTeamSetupLine((
- state: 'incomplete',
- detail: 'the team daemon is not running',
- )),
- "Teammates' agents paused: Harness Team is not finished (the team daemon is not running)",
- );
- expect(
- superTabTeamSetupAction((state: 'incomplete', detail: 'x')),
- 'Repair',
- );
- expect(superTabTeamSetupAction((state: 'failed', detail: null)), 'Set up');
- expect(superTabTeamSetupAction(null), 'Set up');
- });
-
- testWidgets('on a Mac the dialog says what it always said', (tester) async {
- await open(tester);
- expect(shown(tester), [
- 'Set up Harness Team on this Mac',
- 'Teammates\' agents in your Swarms run on this Mac in a separate macOS '
- 'account, Harness Team. They cannot read your files or use your GitHub login. '
- 'They use this Mac\'s Claude Code and Codex subscriptions, so nobody signs in again.',
- 'macOS asks for your password once, in a window titled “osascript”. '
- 'That is the macOS tool Harness uses to ask.',
- paragraph3,
- ]);
- await tester.tap(find.text('Cancel'));
- await tester.pumpAndSettle();
- expect(
- await outcome(tester, 'macos', {'ok': true, 'state': 'started'}),
- 'macOS is asking for your password in a window titled “osascript”. '
- 'After that, setup goes on in the background: this Mac\'s row in '
- 'Machines shows how far it is, and Harness tells you when it is ready.',
- );
- expect(
- await outcome(tester, 'macos', {'ok': true, 'state': 'exists'}),
- 'Harness Team is already set up on this Mac.',
- );
- expect(
- await outcome(tester, 'macos', {'error': 'INVALID_REQUEST'}),
- 'This Mac\'s Harness is too old to set it up from here. Update Harness, '
- 'or run harness team setup in Terminal.',
- );
- expect(
- await outcome(tester, 'macos', {'ok': true, 'state': 'unsupported'}),
- 'Harness Team cannot be set up on this Mac right now.',
- );
- });
-
- testWidgets(
- 'on Linux the dialog says this computer, and the system asks for the password',
- (tester) async {
- await open(tester, operatingSystem: 'linux');
- expect(shown(tester), [
- 'Set up Harness Team on this computer',
- computerParagraph1,
- 'Your system asks for your password once.',
- paragraph3,
- ]);
- expect(find.text('Continue'), findsOneWidget);
- expect(find.text('Cancel'), findsOneWidget);
- await tester.tap(find.text('Cancel'));
- await tester.pumpAndSettle();
- expect(
- await outcome(tester, 'linux', {'ok': true, 'state': 'started'}),
- 'Your system is asking for your password. After that, setup goes on '
- 'in the background: this computer\'s row in Machines shows how far it is, '
- 'and Harness tells you when it is ready.',
- );
- // No desktop session to ask in (the owner's daemon under systemd --user, or SSH): the daemon answers `no-prompt` up
- // front (cli/src/team/autoSetup.ts) and nothing runs, so the terminal is the way.
- expect(
- await outcome(tester, 'linux', {'ok': true, 'state': 'no-prompt'}),
- 'Run harness team setup in a terminal on this computer.',
- );
- expect(
- await outcome(tester, 'linux', {'ok': true, 'state': 'exists'}),
- 'Harness Team is already set up on this computer.',
- );
- expect(
- await outcome(tester, 'linux', {'error': 'INVALID_REQUEST'}),
- 'This computer\'s Harness is too old to set it up from here. Update Harness, '
- 'or run harness team setup in a terminal.',
- );
- expect(
- await outcome(tester, 'linux', {'ok': true, 'state': 'unsupported'}),
- 'Harness Team cannot be set up on this computer right now.',
+ hasLength(1),
);
- },
- );
-
- testWidgets(
- 'on Windows the dialog says this computer, and User Account Control asks',
- (tester) async {
- await open(tester, operatingSystem: 'windows', asked: true);
- expect(shown(tester), [
- 'Set up Harness Team on this computer',
- computerParagraph1,
- 'Windows asks for permission once (User Account Control).',
- paragraph3,
- ]);
- expect(find.text('Not now'), findsOneWidget);
- await tester.tap(find.text('Not now'));
- await tester.pumpAndSettle();
- daemon.asked.clear();
- expect(
- await outcome(tester, 'windows', {'ok': true, 'state': 'started'}),
- 'Windows is asking for permission. After that, setup goes on '
- 'in the background: this computer\'s row in Machines shows how far it is, '
- 'and Harness tells you when it is ready.',
- );
- expect(
- await outcome(tester, 'windows', {'ok': true, 'state': 'exists'}),
- 'Harness Team is already set up on this computer.',
- );
- // A refusal says the daemon's own sentence, as on a Mac.
expect(
- await outcome(tester, 'windows', {
- 'error': 'NO_PROMPT',
- 'detail': 'The daemon\'s sentence.',
- }),
- 'The daemon\'s sentence.',
+ [
+ for (final (type, payload) in f.connection.calls)
+ if (type == 'super_tabs' && _teamSetup(payload)) payload['action'],
+ ],
+ isEmpty,
);
+ await c.flush();
+ f.app.superTabs.dispose();
+ f.dispose();
+ await tester.pump();
},
);
testWidgets(
- 'explains the account and the "osascript" prompt before macOS asks',
+ 'this Mac\'s own row shows no Set up, Repair or Restart for a Team account, '
+ 'and asks its daemon nothing of one',
(tester) async {
- daemon.answer = {'ok': true, 'state': 'started'};
- await open(tester);
- expect(find.textContaining('separate macOS account'), findsOneWidget);
- expect(find.textContaining('titled “osascript”'), findsOneWidget);
- expect(daemon.asked, isEmpty);
- await tester.tap(find.byKey(const Key('team-account-setup-continue')));
- await tester.pumpAndSettle();
- expect(daemon.asked, [
- {'action': 'teamSetup', 'reason': 'manual'},
- ]);
- expect(
- find.byKey(const Key('team-account-setup-outcome')),
- findsOneWidget,
- );
- await tester.tap(find.byKey(const Key('team-account-setup-done')));
- await tester.pumpAndSettle();
- expect(find.byKey(const Key('team-account-setup')), findsNothing);
- },
- );
-
- testWidgets('"Not now" on an offer is remembered; Cancel on Set up is not', (
- tester,
- ) async {
- await open(tester, asked: true);
- await tester.tap(find.text('Not now'));
- await tester.pumpAndSettle();
- await open(tester);
- await tester.tap(find.text('Cancel'));
- await tester.pumpAndSettle();
- expect(daemon.asked, [
- {'action': 'teamSetupDecline'},
- ]);
- });
-
- group('Remove this Mac from the Swarm, the one way out', () {
- Map<String, dynamic> thisMac() => {
- 'machineId': 'm',
- 'name': 'Test host',
- 'contributorId': 'owner',
- 'teamWork': {'allowed': false, 'code': 'TEAM_ACCOUNT_REQUIRED'},
- };
-
- Future<SuperTabLaunchFixture> joined() async {
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- f.connection.teamCheck = {'state': 'wanted'};
- // The Swarm lists this Mac, as the join added it.
- f.connection.server.state['machines'] = [thisMac()];
- await f.app.offerTeamAccount('join', tabId: tabId);
- expect(f.app.teamSetupLocked, isTrue);
- return f;
- }
-
- List<Object?> commands(SuperTabLaunchFixture f) =>
- f.connection.server.posts.map((p) => p['command']).toList();
-
- // Review of #2779: a lock whose Swarms all refused Remove held for good.
- test(
- 'a Swarm that no longer holds this Mac is let go without a command',
- () async {
- final f = await joined();
- f.connection.server.state['machines'] = [];
- expect(await f.app.removeLockedMachine(), isNull);
- expect(
- commands(f),
- isNot(contains(containsPair('type', 'machine.remove'))),
- );
- expect(f.app.teamSetupLocked, isFalse);
- f.app.superTabs.dispose();
- },
- );
-
- test('a Swarm already removing this Mac is let go', () async {
- final f = await joined();
- f.connection.server.state['machines'] = [
- {
- ...thisMac(),
- 'removal': {'requestedAt': 1},
- },
- ];
- // As the Swarm answers a second removal.
- f.connection.server.refuse = {
- 'code': 'MACHINE_REMOVING',
- 'message': 'This machine is already being removed.',
+ final daemon = _Daemon();
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ // A teammate, so the row has someone whose work it would run.
+ final server = ConversationServer();
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ final now = DateTime.now().millisecondsSinceEpoch;
+ Map<String, dynamic> pool(
+ String id,
+ Map<String, dynamic> teamWork, {
+ String? host,
+ int age = 0,
+ }) => {
+ 'machineId': id,
+ 'name': 'MacBook Pro',
+ 'contributorId': 'owner',
+ 'scope': 'swarm',
+ 'cwd': '/swarm',
+ 'engines': ['codex'],
+ 'maxAgents': 4,
+ 'paused': false,
+ 'observation': {'receivedAt': now - age},
+ 'hostMachineId': ?host,
+ 'teamWork': teamWork,
};
- expect(await f.app.removeLockedMachine(), isNull);
- expect(f.app.teamSetupLocked, isFalse);
- f.app.superTabs.dispose();
- });
-
- test('a Swarm this person can no longer open is let go', () async {
- final f = await joined();
- (await f.app.superTabs.open(tabId)).accessRevoked = true;
- expect(await f.app.removeLockedMachine(), isNull);
- expect(f.app.teamSetupLocked, isFalse);
- f.app.superTabs.dispose();
- });
-
- Future<SuperTabLaunchFixture> restarted(List<Object?> machines) async {
- final f = SuperTabLaunchFixture();
- f.app.teamAccountHereForTest = true;
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
- f.connection.teamSetup = {'state': 'none'};
- f.connection.server.state['machines'] = machines;
- f.store.values['team_setup_lock.owner'] = jsonEncode([tabId]);
- f.app.onMachineConnectedForTest('m');
- return f;
- }
-
- test(
- 'a lock restored for a Swarm that still holds this Mac holds',
- () async {
- final f = await restarted([thisMac()]);
- await until(() => f.app.teamSetupLocked);
- f.app.superTabs.dispose();
- },
- );
-
- test(
- 'a lock restored for a Swarm that no longer holds this Mac does not hold',
- () async {
- final f = await restarted([]);
- await until(() => !f.store.values.containsKey('team_setup_lock.owner'));
- expect(f.app.teamSetupLocked, isFalse);
- f.app.superTabs.dispose();
- },
- );
-
- test(
- 'removes this Mac from the Swarm it joined, and ends the lock',
- () async {
- final f = await joined();
- expect(await f.app.removeLockedMachine(), isNull);
+ Map<String, dynamic> refused(String code) => {
+ 'allowed': false,
+ 'code': code,
+ 'reason': 'Refused ($code).',
+ };
+ for (final machines in [
+ // No Team account here: once offered Set up.
+ [pool('m', refused('TEAM_ACCOUNT_REQUIRED'))],
+ // Its Team account offline: once offered Restart.
+ [
+ pool('m', {'allowed': true}),
+ pool(
+ 'm-team',
+ refused('MACHINE_OFFLINE'),
+ host: 'm',
+ age: 10 * 60 * 1000,
+ ),
+ ],
+ ]) {
+ server.state['machines'] = machines;
+ final c = server.controller(account: 'owner');
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMachines(
+ controller: c,
+ app: app,
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
expect(
- f.connection.server.posts.map((p) => p['command']),
- contains(equals({'type': 'machine.remove', 'machineId': 'm'})),
+ find.byKey(const ValueKey('super-machine-team-setup-m')),
+ findsNothing,
);
- expect(f.app.teamSetupLocked, isFalse);
- f.app.superTabs.dispose();
- },
- );
-
- test('a removal the Swarm refuses says why and keeps the lock', () async {
- final f = await joined();
- f.connection.server.refuse = {
- 'code': 'FORBIDDEN',
- 'message': 'Only the Swarm owner can do that.',
- };
- expect(
- await f.app.removeLockedMachine(),
- 'Only the Swarm owner can do that.',
- );
- expect(f.app.teamSetupLocked, isTrue);
- f.app.superTabs.dispose();
- });
- });
+ for (final word in ['Set up', 'Repair', 'Restart']) {
+ expect(find.widgetWithText(OutlinedButton, word), findsNothing);
+ }
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ }
+ expect(daemon.asked, isEmpty);
+ app.dispose();
+ },
+ );
}
diff --git a/desktop/test/team_setup_background_test.dart b/desktop/test/team_setup_background_test.dart
deleted file mode 100644
index f55b20f74..000000000
--- a/desktop/test/team_setup_background_test.dart
+++ /dev/null
@@ -1,404 +0,0 @@
-// #3169 (Scholes, 2026-11-05): after the password, Harness Team setup took 5 to 7 minutes and held the whole app. It now
-// runs in the background: the lock steps aside once the password is accepted, this Mac's row in Machines says the step
-// and the time left, and a notice says when it is ready or failed, with Retry. Nothing here opens a socket, signs the
-// CLI in or out, or makes a macOS account: the daemon's answers are a fake's.
-import 'dart:io';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/core/models.dart';
-import 'package:harness/state/app_state.dart';
-import 'package:harness/super_tabs/machines.dart';
-import 'package:harness/super_tabs/team_account_setup.dart';
-
-import 'support/capture.dart';
-import 'support/rename_connection.dart';
-import 'support/super_tab_fixture.dart';
-import 'swarm_state_test.dart' show createApp;
-
-/// This Mac's daemon for the Harness Team account's actions.
-class _Daemon extends RenameConnection {
- final asked = <String>[];
- Map<String, dynamic> check = {'ok': true, 'state': 'wanted'};
- Map<String, dynamic> run = {'ok': true, 'state': 'started'};
-
- /// `teamSetupStatus`, in turn; the last one repeats.
- final statuses = <Map<String, dynamic>>[
- {'ok': true, 'state': 'running'},
- ];
-
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) async {
- final action = '${payload['action']}';
- if (type == 'super_tabs' && action.startsWith('teamSetup')) {
- asked.add(action);
- return switch (action) {
- 'teamSetupCheck' => check,
- 'teamSetup' => run,
- 'teamSetupStatus' =>
- statuses.length > 1 ? statuses.removeAt(0) : statuses.single,
- _ => {'ok': true},
- };
- }
- return super.request(type, payload: payload, timeout: timeout);
- }
-}
-
-Map<String, dynamic> _running(String step, {int elapsedMs = 20000}) => {
- 'ok': true,
- 'state': 'running',
- 'step': step,
- 'elapsedMs': elapsedMs,
-};
-
-/// Set to a folder to write the PR's pictures there.
-final shots = Platform.environment['TEAM_SETUP_SHOTS'];
-
-void main() {
- TestWidgetsFlutterBinding.ensureInitialized();
- setUpAll(() => loadCaptureFonts(shots));
- late _Daemon daemon;
- late AppNotifier app;
-
- setUp(() {
- daemon = _Daemon();
- app = createApp(connectionForTest: (_) => daemon, connected: true);
- app.currentUser = const CurrentUserProfile(
- id: 'owner',
- email: '[email protected]',
- );
- app.machineStates['m']!.localOnly = true;
- app.teamAccountHereForTest = true;
- });
- tearDown(() => app.dispose());
-
- group('the time left', () {
- test('four steps, from the eight setup says', () {
- expect(
- [
- for (final step in [
- 'password',
- 'account',
- 'home',
- 'privacy',
- 'runtime',
- 'copy-engines',
- 'engines',
- 'sign-in',
- 'daemon',
- 'report',
- 'something-new',
- ])
- teamSetupPhase(step),
- ],
- [null, 1, 1, 1, 2, 2, 2, 3, 3, 4, null],
- );
- });
-
- test('from the measured step times, never nothing while it runs', () {
- // The npm download is the long one (4 min 18 s on 2026-11-04); the copy that replaced it takes seconds.
- expect(
- teamSetupLine('engines', Duration.zero),
- 'Harness Team: setting up · step 2 of 4 · about 4 min left',
- );
- expect(
- teamSetupLine('copy-engines', Duration.zero),
- 'Harness Team: setting up · step 2 of 4 · less than a minute left',
- );
- expect(
- teamSetupLine('account', Duration.zero),
- 'Harness Team: setting up · step 1 of 4 · less than a minute left',
- );
- expect(
- teamSetupLine('engines', const Duration(minutes: 2)),
- 'Harness Team: setting up · step 2 of 4 · about 2 min left',
- );
- // Past what it usually takes (a slow network), it still says a minute is left, never zero.
- expect(
- teamSetupLine('engines', const Duration(minutes: 9)),
- 'Harness Team: setting up · step 2 of 4 · about 1 min left',
- );
- expect(
- teamSetupLine('report', const Duration(minutes: 9)),
- 'Harness Team: setting up · step 4 of 4 · less than a minute left',
- );
- // A step this app does not know yet: setting up, without a number it cannot give.
- expect(
- teamSetupLine('something-new', Duration.zero),
- 'Harness Team: setting up',
- );
- });
- });
-
- group('in the background', () {
- final messenger = GlobalKey<ScaffoldMessengerState>();
- var taps = 0;
-
- /// The window as app_shell.dart builds it, the lock above the Navigator, with this Mac's row in Machines when
- /// [server] is given.
- /// Its Swarm's controller, for [unmount].
- dynamic shown;
-
- Future<void> window(
- WidgetTester tester, {
- ConversationServer? server,
- }) async {
- taps = 0;
- final c = server?.controller(account: 'owner');
- shown = c;
- if (c != null) await c.refresh();
- await tester.pumpWidget(
- MaterialApp(
- scaffoldMessengerKey: messenger,
- builder: (context, child) => TeamAccountSetupLock(
- app: app,
- operatingSystem: 'macos',
- child: child!,
- ),
- home: Scaffold(
- body: Column(
- children: [
- TextButton(
- key: const Key('behind-button'),
- onPressed: () => taps++,
- child: const Text('Behind'),
- ),
- if (c != null)
- Expanded(
- child: SuperTabMachines(
- controller: c,
- app: app,
- onAddAgent: (_) {},
- ),
- ),
- ],
- ),
- ),
- ),
- );
- await tester.pump();
- }
-
- ConversationServer swarm() {
- final server = ConversationServer();
- (server.state['people'] as List).add({
- 'id': 'peer',
- 'email': '[email protected]',
- 'role': 'collaborator',
- });
- server.state['machines'] = [
- {
- 'machineId': 'm',
- 'name': 'MacBooks-MacBook-Pro-7',
- 'contributorId': 'owner',
- 'scope': 'swarm',
- 'cwd': '/swarm',
- 'engines': ['codex'],
- 'maxAgents': 4,
- 'paused': false,
- 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
- 'teamWork': {
- 'allowed': false,
- 'code': 'TEAM_ACCOUNT_REQUIRED',
- 'reason': 'Refused.',
- },
- },
- ];
- return server;
- }
-
- Future<void> continueSetup(WidgetTester tester) async {
- await app.offerTeamAccount('join', tabId: 'tab-1');
- await tester.pump();
- await tester.tap(find.byKey(const Key('team-account-lock-continue')));
- await tester.pump();
- }
-
- testWidgets(
- 'once the password is accepted the lock steps aside and the app takes clicks, while setup still runs',
- (tester) async {
- daemon.statuses
- ..clear()
- ..addAll([_running('password'), _running('engines')]);
- await window(tester);
- await continueSetup(tester);
- // While macOS asks for the password, the lock waits with it.
- await tester.pump(const Duration(seconds: 2));
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- await tester.tap(
- find.byKey(const Key('behind-button')),
- warnIfMissed: false,
- );
- expect(taps, 0);
- // The password is in: setup goes on behind, and the app is the person's again.
- await tester.pump(const Duration(seconds: 2));
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- expect(app.teamSetupLocked, isTrue);
- await tester.tap(find.byKey(const Key('behind-button')));
- expect(taps, 1);
- expect(TeamSetupWatch.of(app)!.running, isTrue);
- },
- );
-
- testWidgets(
- 'this Mac\'s row says the step and the time left, and that the person can keep working',
- (tester) async {
- daemon.statuses
- ..clear()
- ..add(_running('engines'));
- await window(tester, server: swarm());
- await continueSetup(tester);
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- expect(
- tester
- .widget<Text>(
- find.byKey(const ValueKey('super-machine-problem-m')),
- )
- .data,
- 'Harness Team: setting up · step 2 of 4 · about 4 min left\n'
- 'Keep working. We\'ll tell you when it\'s ready.',
- );
- // Nothing to press while it runs: Set up would ask for the password again.
- expect(
- find.byKey(const ValueKey('super-machine-team-setup-m')),
- findsNothing,
- );
- // Past the row's arrival fade, for the picture.
- await tester.pump(const Duration(milliseconds: 1500));
- await captureWindow(tester, shots, 'row-setting-up');
- await tester.pumpWidget(const SizedBox());
- await shown.flush();
- shown.dispose();
- },
- );
-
- testWidgets(
- 'a setup that finishes says so, and the lock is gone for good',
- (tester) async {
- daemon.statuses
- ..clear()
- ..addAll([
- _running('engines'),
- {'ok': true, 'state': 'exists'},
- ]);
- await window(tester);
- await continueSetup(tester);
- await tester.pump(const Duration(seconds: 2));
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 500));
- expect(
- find.text(
- 'Harness Team is ready on this Mac. Teammates\' agents can run here now.',
- ),
- findsOneWidget,
- );
- expect(app.teamSetupLocked, isFalse);
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await captureWindow(tester, shots, 'notice-ready');
- // Nothing is read once it has ended.
- final reads = daemon.asked.where((a) => a == 'teamSetupStatus').length;
- await tester.pump(const Duration(seconds: 10));
- expect(
- daemon.asked.where((a) => a == 'teamSetupStatus'),
- hasLength(reads),
- );
- },
- );
-
- testWidgets(
- 'a setup that fails after the lock stepped aside brings it back, with the reason and Try again',
- (tester) async {
- daemon.statuses
- ..clear()
- ..addAll([
- _running('engines'),
- {
- 'ok': true,
- 'state': 'failed',
- 'detail': 'launchd would not start the team daemon',
- },
- ]);
- await window(tester);
- await continueSetup(tester);
- await tester.pump(const Duration(seconds: 2));
- expect(find.byKey(const Key('team-account-lock')), findsNothing);
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- expect(find.byKey(const Key('team-account-lock')), findsOneWidget);
- expect(
- tester
- .widget<Text>(find.byKey(const Key('team-account-lock-outcome')))
- .data,
- 'Setup did not finish: launchd would not start the team daemon.',
- );
- expect(
- find.byKey(const Key('team-account-lock-retry')),
- findsOneWidget,
- );
- },
- );
-
- testWidgets(
- 'started from this Mac\'s row, a failure is a notice with the reason and Retry, and Retry starts it again',
- (tester) async {
- daemon.statuses
- ..clear()
- ..addAll([
- _running('runtime'),
- {'ok': true, 'state': 'failed', 'detail': 'dscl exited 64.'},
- ]);
- await window(tester);
- expect(app.teamSetupLocked, isFalse);
- // What the row's Set up does once its dialog's Continue has started setup.
- TeamSetupWatch.of(app)!.follow();
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 500));
- expect(
- find.text('Harness Team setup did not finish. dscl exited 64.'),
- findsOneWidget,
- );
- await captureWindow(tester, shots, 'notice-failed');
- daemon.statuses
- ..clear()
- ..add(_running('password'));
- await tester.tap(find.byKey(const Key('team-setup-notice-retry')));
- await tester.pump();
- await tester.pump();
- expect(daemon.asked.where((a) => a == 'teamSetup'), hasLength(1));
- expect(TeamSetupWatch.of(app)!.running, isTrue);
- messenger.currentState?.clearSnackBars();
- },
- );
-
- testWidgets('a closed password window, from the row, says so with Retry', (
- tester,
- ) async {
- daemon.statuses
- ..clear()
- ..add({'ok': true, 'state': 'declined'});
- await window(tester);
- TeamSetupWatch.of(app)!.follow();
- await tester.pump(const Duration(seconds: 2));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 500));
- expect(
- find.text(
- 'Harness Team setup did not finish. The password window was closed.',
- ),
- findsOneWidget,
- );
- expect(find.byKey(const Key('team-setup-notice-retry')), findsOneWidget);
- messenger.currentState?.clearSnackBars();
- });
- });
-}
diff --git a/desktop/test/windows_words_test.dart b/desktop/test/windows_words_test.dart
index ca5437ea8..e785e46e9 100644
--- a/desktop/test/windows_words_test.dart
+++ b/desktop/test/windows_words_test.dart
@@ -15,7 +15,6 @@ const _sayMacBehindACheck = {
'lib/shared/theme/appearance_prefs_store.dart',
'lib/shortcuts/shortcut_recorder.dart',
'lib/state/harness_monitor.dart',
- 'lib/super_tabs/team_account_setup.dart',
'lib/super_tabs/voice_row.dart',
'lib/autonomous_device/autonomous_device_cli.dart',
'lib/devices/wifi_robots.dart',
diff --git a/docs/plans/2026-11-07-own-permission-settings-plan.md b/docs/plans/2026-11-07-own-permission-settings-plan.md
new file mode 100644
index 000000000..2a84e0fcc
--- /dev/null
+++ b/docs/plans/2026-11-07-own-permission-settings-plan.md
@@ -0,0 +1,133 @@
+# Agents start with their owner's own permission settings: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** task #4215 (from anh Dee's Buddy's review of main 0413586e, Swarm v3). Every Swarm PM, agent and Buddy starts with
+its owner's own Claude Code or Codex settings: Harness sends no permission mode unless the person chose one (Cmd-N, the
+agent's menu, `harness new --mode`), and never writes full mode's warning acceptance into the person's settings. Anthropic
+says to use `--dangerously-skip-permissions` only in isolated environments; a person's own Mac is not one.
+
+**Findings, each verified on main 0413586e:**
+
+1. Real. `cli/src/superTabs/start.ts:259`: `harness super-tab start` sends `permissionMode: 'full'` on every start.
+2. Real, and a second site the review did not name: the machine host builds the launch with `bypassPermission: true` and
+ `permissionMode: 'full'` whatever the request said (`cli/src/superTabs/start.ts:458-459`).
+3. Real. `backend/src/superTabs/machines.ts:867` admits only `full`, and its refusal says "with full permissions for Swarm
+ agents".
+4. Real. `cli/src/core/agents/create.ts:314` writes `skipDangerousModePermissionPrompt: true` into the person's
+ `~/.claude/settings.json` (or `CLAUDE_CONFIG_DIR`) for every Swarm agent in full mode (`engines/claude/launch.ts:57`).
+5. Real (marked review). `harness new claude` with no `--mode` sends `permissionMode: 'auto'`: the parser defaults `mode` to
+ `auto` and `newAgentPayload` sends it whenever the engine has that mode (`cli/src/lib/newCommand.ts:106,233-234`).
+
+**Architecture:**
+
+- Backend: `admitMachineStart` refuses any `permissionMode` on `agent.start`, in the words a CLI from before full mode already
+ answers by sending the start again without it (`Refused: permissionMode (it runs with its own default account settings, so
+ leave it out).`, last in the list). So CLIs from the last 30 days keep starting agents.
+- CLI, the PM's side: the start request carries no `permissionMode`; the older-backend retry for that field and its warning go.
+- CLI, the machine host: the launch payload has no `permissionMode` and `bypassPermission: false`, so the engine opens in the
+ person's own default mode (no flag: `lib/engineLaunch.ts buildEngineLaunchArgv`). A Team-written start keeps `teamWritten`,
+ its barrier against the branch's own settings, in a Team home that is no person's (no new start reaches one since #4120).
+- Daemon: `acceptFullMode` and the contract behind it (`bypassAcceptance`, `recordAcceptanceIn`) are removed. A person who
+ chooses full mode answers Claude Code's own warning once, as in their own terminal.
+- Daemon: the Swarm folder trust (create.ts `trustSwarmFolder`, launches.ts `swarmAgent`) was keyed on full mode as a proxy
+ for "the Swarm made this checkout". It is keyed on the Swarm role alone, with every other guard kept (local frame, a clone
+ in the projects root or a worktree Harness made, Claude Code only). Without this, a PM in the person's own mode would sit at
+ "Do you trust this folder?" again (2026-10-26, 2026-10-30).
+- `harness new`: a mode is sent only when typed (`--mode`, `--plan`).
+
+**Tech Stack:** TypeScript, vitest (cli and backend unit tests), backend integration tests.
+
+**Spec:** the task's brief (#4215).
+
+## Global Constraints
+
+- Never read or print a secret or login.
+- Test first: each plan task commits its failing test, then the code.
+- Older CLIs (last 30 days) keep starting Swarm agents against the new backend.
+
+## Review Focus
+
+- An older CLI that sends `full` to the new backend: refused in the exact words it retries on, then admitted without it.
+- A Swarm PM in the person's own mode in a fresh clone or worktree: still trusted, so it never sits at the trust question.
+- A relayed (non-local) start, or a folder Harness did not make: still not trusted, whatever the role.
+- A Team-written start: still `teamWritten`.
+- `harness new` for an engine without a mode row: still no mode, as before.
+
+## Clients (added by the PM, 2026-11-07)
+
+Desktop's Cmd+S Swarm PM (`desktop/lib/super_tabs/launch.dart:129 forcedPermissionMode: 'full'`) and the phone's Swarm PM
+(`mobile/lib/swarm/swarm_computers.dart:184`) forced full mode from the client; with the acceptance write gone, such a PM on
+a machine that never accepted full mode would stop at Claude Code's warning. The PM put both in this task (Tasks 5 and 6).
+
+---
+
+### Task 1: the backend admits no permission mode on a Swarm start
+
+**Files:**
+- Modify: `backend/src/superTabs/machines.ts:866-871`
+- Test: `backend/src/superTabs/machines.test.ts`, `backend/integration/superTabs.test.ts`, `backend/integration/superTabGithub.test.ts`
+
+- [ ] Test: `refuses every permission mode, full included, in the words older CLIs retry without it`: for `full`, `ask`, `auto`,
+ `bypass` the error is `OUTSIDE_CONTRIBUTION` and its message ends with
+ `Refused: permissionMode (it runs with its own default account settings, so leave it out).`; a start without it is admitted.
+ Integration requests drop `permissionMode: 'full'`; the queued request has no `permissionMode`.
+- [ ] Run, see it fail; implement; run, see it pass; commit each.
+
+### Task 2: a Swarm start sends no permission mode, and the host launches with none
+
+**Files:**
+- Modify: `cli/src/superTabs/start.ts:251-282, 458-459`
+- Test: `cli/src/superTabs/start.spec.ts`
+
+- [ ] Test: the `agent.start` request has no `permissionMode` (the heavy retry too); the host's `agent_create` payload has no
+ `permissionMode` and `bypassPermission: false` for Claude and Codex, agent and Buddy; `teamWritten` unchanged. Tests of the
+ removed older-backend retry are removed.
+- [ ] Run, see it fail; implement; run, see it pass; commit each.
+
+### Task 3: the daemon writes nothing into the person's settings, and still trusts a Swarm checkout
+
+**Files:**
+- Modify: `cli/src/core/agents/create.ts`, `cli/src/core/agents/launches.ts`, `cli/src/engines/launchPrep.ts`,
+ `cli/src/engines/claude/launch.ts`, `cli/src/engines/facets/launch.ts`, `cli/src/engines/kit/folderTrust.ts`
+- Test: `cli/src/core/agents/create.spec.ts`, `cli/src/core/agents/launches.spec.ts`, `cli/src/engines/launchPrep.spec.ts`,
+ `cli/src/engines/kit/folderTrust.spec.ts`
+
+- [ ] Test: a Swarm agent created with no mode, and one in full mode, leaves a real throwaway `CLAUDE_CONFIG_DIR/settings.json`
+ untouched; a local Claude Swarm agent with no mode in a projects-root clone, a Harness worktree or a remote checkout is
+ trusted; relayed, non-Swarm, a handed folder and Codex are not.
+- [ ] Run, see it fail; implement (remove `acceptFullMode`, `bypassAcceptance`, `recordAcceptanceIn`; drop the mode condition
+ from the two trust checks); run, see it pass; run `npm run test:core`; commit each.
+
+### Task 4: `harness new` sends a mode only when typed
+
+**Files:**
+- Modify: `cli/src/lib/newCommand.ts:233-237`
+- Test: `cli/src/lib/newCommand.spec.ts`
+
+- [ ] Test: `harness new claude` and `harness new codex` send neither `permissionMode` nor `bypassPermission: true`;
+ `--mode auto`, `--mode full`, `--plan` still send theirs.
+- [ ] Run, see it fail; implement; run, see it pass; commit each.
+
+### Task 5: Desktop starts a Swarm PM in the mode the person chose
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/launch.dart`, `desktop/lib/state/harness_launch_integration.dart`,
+ `desktop/lib/state/new_harness.dart`, `desktop/lib/super_tabs/personal_lead.dart`
+- Test: `desktop/test/super_tab_launch_test.dart`, `desktop/test/super_tab_personal_lead_test.dart`
+
+- [ ] Test: a new Swarm, new project and member start of Claude and Codex shows Permissions and sends the person's mode
+ (`ask`, bypass off); OpenCode and Hermes members launch as their ordinary harness; the personal PM sends no mode and
+ `bypassPermission: false` (Desktop's `createAgent` defaults it to true).
+- [ ] Run, see it fail; remove `forcedPermissionMode`; the Permissions row is hidden only when the Swarm starts the PM on
+ another machine (`leadThroughSwarm`), which cannot take a choice; run, see it pass; commit each.
+
+### Task 6: the phone starts a Swarm PM with no mode
+
+**Files:**
+- Modify: `mobile/lib/swarm/swarm_computers.dart`
+- Test: `mobile/test/swarm/swarm_lead_computers_test.dart`
+
+- [ ] Test: `startLead` sends no `permissionMode` and `bypassPermission: false`.
+- [ ] Run, see it fail; drop `permissionMode: 'full'`; run, see it pass; commit each.
diff --git a/docs/plans/2026-11-07-team-leftovers-plan.md b/docs/plans/2026-11-07-team-leftovers-plan.md
new file mode 100644
index 000000000..d1841e604
--- /dev/null
+++ b/docs/plans/2026-11-07-team-leftovers-plan.md
@@ -0,0 +1,115 @@
+# Remove Team-account leftovers: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** Swarm v3 has no Team accounts (anh Dee, 2026-11-07; #4120 stopped new work reaching one). Task #4221 removes
+what still offers, runs or describes one: nothing offers to set up a Team account, an existing Team account's boot daemon
+stops for good on update once no agent runs in it, and the agents' manual, skills and Desktop stop telling people work runs
+in one.
+
+**Architecture:**
+
+- Owner's daemon (cli/src/superTabs/service.ts): the four `teamSetup*` actions, `teamAccountsIn` and `sharedSwarm` go, and
+ with them cli/src/team/autoSetup.ts, which only they used. A Desktop from before asks them, gets an error, and its own
+ catch already treats that as "nothing to offer" (app_state.dart `offerTeamAccount`, `teamSetupProgress`). The read's
+ `teamAccounts` flag (swarmReads.ts, readContract.ts, the read fixtures) goes: the backend never sends `false` since the
+ allowlist went (#2505), which is why the offer ran in every Swarm.
+- `harness team setup` refuses with `TEAM_ACCOUNTS_REMOVED` before it asks for an administrator. `harness team remove`
+ stays: it is how a person deletes the account and its home when they choose to.
+- The Team account's own daemon (cli/src/superTabs/inCore/teamRetire.ts, new, wired in core/main.ts): when the Team
+ config names this OS user (team/config.ts `isTeamAccount`), it stops for good the first time the core has no active
+ agent session, checked as it starts and whenever the session list changes. It stops with the core's existing
+ stop-for-good exit (`forGood`, a new reason `retired`), so launchd (`KeepAlive.SuccessfulExit false`), systemd
+ (`Restart=on-failure`) and the Windows task leave it stopped until the next boot, where it starts, finds no agent and
+ stops again. Its files are root's: removing them needs an administrator prompt, which nothing opens unasked
+ (AGENTS.md, Windows); `harness team remove` removes them. A computer signed in with `harness team on` is not a Team
+ account and is untouched.
+- Agents' manual and skills (cli/src/lib/swarmTools.ts, swarmToolSheets.ts, swarmSkills.ts): the Team-account lines go.
+- Desktop (desktop/lib): the startup and contribution offers, the setup lock, the Team setup screen
+ (super_tabs/team_account_setup.dart) and every Set up button go; copy that says work runs in a Team account is fixed.
+ Copy about an existing Team account's machine (offline, refusing a person's own request) stays while such machines exist.
+
+**Tech Stack:** TypeScript CLI (vitest), Flutter Desktop (flutter test). **Spec:** task #4221 brief; anh Dee's Swarm v3
+decision (project instructions, PM notes 2026-11-07); docs/plans/2026-11-07-remove-team-accounts-plan.md.
+
+## Global Constraints
+
+- Never delete a person's data: no account, home folder, worktree or session file is removed by an update.
+- Stop only what Harness installed: only the Team account's own daemon stops, and only itself.
+- Never stop a Team daemon while an agent session is active in it (#4120: Team agents finish what they hold).
+- Never read or print a secret or login.
+- Owns cli/src/ and desktop/lib/.
+
+## Design
+
+- growth: N/A because nothing new is stored; the Team setup decision file stops being written.
+- concurrency: N/A because the stop is one process deciding about itself.
+- read cost: one count of the core's in-memory active sessions per session change.
+- scale: N/A because no server or query changes.
+- compatibility: no backend change. A Desktop from the last 30 days asks the removed actions, gets an error, and offers
+ nothing (its existing catch). A Team daemon from before keeps running until it updates to this release.
+- migration and rollback: none; revert. A rolled-back Team daemon starts again at its next boot.
+- audience: N/A because nothing is exposed.
+- identity: N/A because nothing runs under a new login.
+- failure: the Team daemon logs `[team] Swarm v3 has no Team accounts: no agent runs here, stopping for good` before it
+ stops; `harness team status` says it is stopped and that `harness team remove` removes it.
+- platforms: macOS, Linux, Windows (the CLI); macOS, Linux, Windows Desktop. Tested on macOS; CI runs Linux.
+
+## Review Focus
+
+1. A Team daemon with an agent still active is never stopped (an agent reattached after a restart counts).
+2. The owner's own daemon on a Mac that has a Team account never stops (the config names another user).
+3. A `harness team on` computer (a Team sign-in, no Team config for this user) never stops.
+4. A Desktop from before against the new daemon offers nothing and never locks.
+5. No Desktop path still opens the Team setup screen (the machine row, the import dialog, the startup ask).
+
+---
+
+### Task 1: the owner's daemon offers no Team account; `harness team setup` refuses
+
+**Files:** Modify cli/src/superTabs/service.ts, swarmReads.ts, readContract.ts, fixtures/read/index.ts, team/command.ts;
+delete team/autoSetup.ts and its spec. Test: superTabs/service.spec.ts, team/command.spec.ts.
+
+**Interfaces:** Produces the refusal code `TEAM_ACCOUNTS_REMOVED` (team/command.ts).
+
+- [ ] Test: `teamSetupCheck` for `startup`, `contribute`, `join` and `manual`, with a read that fails, runs no setup and
+ answers an error; `teamSetup` and `teamSetupStatus` the same.
+- [ ] Test: `harness team setup` answers `TEAM_ACCOUNTS_REMOVED` and runs no administrator script.
+- [ ] Watch both fail; commit.
+- [ ] Remove the actions, `teamAccountsIn`, `sharedSwarm`, autoSetup.ts and the `teamAccounts` read flag; make setup refuse.
+- [ ] Watch them pass with the touched specs (service, swarmReads, team/command); commit.
+
+### Task 2: a Team account's daemon stops for good once no agent runs in it
+
+**Files:** Create cli/src/superTabs/inCore/teamRetire.ts and its spec; modify superTabs/inCore.ts, core/main.ts
+(`forGood` and the wiring), team/command.ts (status line).
+
+**Interfaces:** Produces `retireTeamDaemon(deps: { teamAccount: boolean; active: () => number; onChange: (listener: () =>
+void) => void; stop: (reason: 'retired') => void; log: (line: string) => void }): void`.
+
+- [ ] Test: a Team account with 0 active stops once with `retired`; with 2 it waits and stops when the count reaches 0;
+ a later change does not stop it twice; not a Team account never stops.
+- [ ] Test (core): `retired` is a stop for good (the supervised exit is `CORE_EXIT_STOP`).
+- [ ] Test: `harness team status` with the daemon installed and not loaded says `harness team remove` removes it.
+- [ ] Watch them fail; commit; implement; watch them pass; commit.
+
+### Task 3: the agents' manual and skills say nothing of Team accounts
+
+**Files:** cli/src/lib/swarmTools.ts, swarmToolSheets.ts (lines and their hashes), swarmSkills.ts. Test:
+lib/swarmTools.spec.ts.
+
+- [ ] Test: the manual, every role's sheet and every role skill contain no "Team account" or "Team agent".
+- [ ] Watch it fail; commit; remove the lines; watch the swarm tool, sheet and skill specs pass; commit.
+
+### Task 4: Desktop offers no Team account and says no work runs in one
+
+**Files:** desktop/lib/state/app_state.dart, app_shell.dart, screens/swarm_screen.dart, super_tabs/machines.dart,
+add_computers.dart, import_agent_dialog.dart, import_agent.dart, core/permission_modes.dart, state/new_harness.dart;
+delete super_tabs/team_account_setup.dart. Tests: desktop/test/team_account_offer_test.dart (rewritten to the new
+rule), team_account_lock_test.dart and team_setup_background_test.dart (deleted with what they pin).
+
+- [ ] Test: at startup and after adding this Mac to a Swarm, Desktop sends no `teamSetup*` request and never locks; the
+ machine row and the import dialog show no Set up.
+- [ ] Watch it fail; commit; remove the offers, the lock, the screen and the buttons; fix the copy; watch the touched
+ tests pass; commit.
diff --git a/mobile/lib/swarm/swarm_computers.dart b/mobile/lib/swarm/swarm_computers.dart
index 44614e53c..0d31fbe81 100644
--- a/mobile/lib/swarm/swarm_computers.dart
+++ b/mobile/lib/swarm/swarm_computers.dart
@@ -165,7 +165,8 @@ class AppSwarmComputers extends ChangeNotifier
}
/// Starts the Lead on [machineId] as Desktop's card does (personal_lead.dart
- /// `_launch`): approving everything, as a Swarm agent, with the Lead's
+ /// `_launch`): with its owner's own permission settings (no mode, task
+ /// #4215), as a Swarm agent, with the Lead's
/// prompt and Claude's Lead model, in the repo's folder or a new one named
/// after the project.
@override
@@ -181,7 +182,6 @@ class AppSwarmComputers extends ChangeNotifier
projectFolder: launch.folder == null
? ProjectFolderRequest.forTask(launch.projectName)
: null,
- permissionMode: 'full',
prompt: launch.prompt,
swarmRole: 'lead',
swarmSkillMode: launch.skillMode,
diff --git a/mobile/test/swarm/swarm_lead_computers_test.dart b/mobile/test/swarm/swarm_lead_computers_test.dart
index f4edd1503..87b9560a0 100644
--- a/mobile/test/swarm/swarm_lead_computers_test.dart
+++ b/mobile/test/swarm/swarm_lead_computers_test.dart
@@ -161,7 +161,10 @@ void main() {
final asked = rig.conn('m').payloadsOf('agent_create').single;
expect(asked['engine'], 'claude');
expect(asked['cwd'], '/Users/me/games');
- expect(asked['permissionMode'], 'full');
+ // Swarm v3 (task #4215): the PM starts with its owner's own permission
+ // settings: no mode, nothing approved for them.
+ expect(asked.containsKey('permissionMode'), isFalse);
+ expect(asked['bypassPermission'], isFalse);
expect(asked['swarmRole'], 'lead');
expect(asked['swarmSkillMode'], 'default');
expect(asked['prompt'], 'Harness Swarm agent. You are the Lead.');