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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness Team account: it signs in as its machine, joins the Swarm and wakes by itself (#1705)
Dee0b45d41d54b1
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 78bce7d74..e56b6ab1e 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -521,7 +521,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst member = candidate.kind === 'member' ? state.agents.find(a => a.id === candidate.agentId) : undefinedif (candidate.kind === 'member' && !member) return null// A new agent on a Mac for a teammate's project runs in the Mac's Harness Team account (machines.ts teamStartRequest).- const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle)+ const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle, context.teamMachines)const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === machineId)?.contributorId ?? starterreturn teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines)}@@ -1035,7 +1035,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')}// A teammate's project started on a Mac runs in that Mac's Harness Team account, never as its owner (machines.ts).- const request = teamStartRequest(state, command.request, home, context.teamAccountsIdle)+ const request = teamStartRequest(state, command.request, home, context.teamAccountsIdle, context.teamMachines)const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines)// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex a1a75bd62..2414b2102 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -150,7 +150,10 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =const reading = pool.observation, name = pool.nameif (!teamRow && reading?.sessionKind !== 'team' && !teamAccountRequired()) return nullif (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {- return { code: 'MACHINE_OFFLINE', reason: `${name} is offline, so it cannot show that its Harness Team account is private.` }+ // A Mac's team account goes by its Mac's name ("One machine"), and the Mac itself may well be online.+ return { code: 'MACHINE_OFFLINE', reason: pool.hostMachineId+ ? `The Harness Team account on ${name} is offline, so it cannot show that it is private.`+ : `${name} is offline, so it cannot show that its Harness Team account is private.` }}if (!teamRow && reading.sessionKind !== 'team') return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `${name} has no Harness Team account yet, ${ONLY_OWN}.` }const privacy = reading.privacy@@ -198,19 +201,21 @@ export function teamPoolsOf(state: SuperTabState, pool: ContributedMachine): Con}/** The one of them that runs teammates' work on the Mac: not being removed, and the last to report. Undefined when none. */-export function teamPoolOf(state: SuperTabState, pool: ContributedMachine): ContributedMachine | undefined {- return teamPoolsOf(state, pool).filter(m => !m.removal)+export function teamPoolOf(state: SuperTabState, pool: ContributedMachine, live?: readonly string[]): ContributedMachine | undefined {+ // [live]: the account rows still signed in as team accounts (store.ts teamMachines). One removed since (`harness team+ // remove` deletes its machine) leaves its pool behind, and the Mac goes back to what a Mac without one does.+ return teamPoolsOf(state, pool).filter(m => !m.removal && (!live || live.includes(m.machineId))).reduce<ContributedMachine | undefined>((best, m) => !best || (m.observation?.receivedAt ?? -1) >= (best.observation?.receivedAt ?? -1) ? m : best, undefined)}/** Where a new agent for [project] runs when a start names [machineId]: the Mac's team account when the project is not* its contributor's own and the Mac has one in this Swarm, else the machine named. */-export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false): string {+export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[]): string {// With no GitHub App on this server a team account cannot fetch or push, so the work stays on the Mac, as before.if (idle) return machineIdconst pool = state.machines?.find(m => m.machineId === machineId)if (!pool || project.ownerId === pool.contributorId) return machineId- return teamPoolOf(state, pool)?.machineId ?? machineId+ return teamPoolOf(state, pool, live)?.machineId ?? machineId}/** The folder a start for [project] uses on [pool]: what admitMachineStart accepts there. */@@ -225,8 +230,9 @@ export function projectFolder(pool: ContributedMachine, project: SwarmProject):* place of the Mac's own for that project. Every other start is returned as it is, so the Mac's owner's own projects* stay with the owner's daemon, and a Mac without a team account here refuses it as before (teamWorkCheck).*/-export function teamStartRequest(state: SuperTabState, request: AgentStartRequest, project: SwarmProject, idle = false): AgentStartRequest {- const machineId = teamMachineFor(state, request.machineId, project, idle)+export function teamStartRequest(state: SuperTabState, request: AgentStartRequest, project: SwarmProject, idle = false,+ live?: readonly string[]): AgentStartRequest {+ const machineId = teamMachineFor(state, request.machineId, project, idle, live)if (machineId === request.machineId) return requestconst pool = state.machines!.find(m => m.machineId === request.machineId)!, team = state.machines!.find(m => m.machineId === machineId)!return { ...request, machineId, cwd: request.cwd === projectFolder(pool, project) ? projectFolder(team, project) : request.cwd }diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.tsindex 77941405b..90063e326 100644--- a/backend/src/superTabs/teamRouting.test.ts+++ b/backend/src/superTabs/teamRouting.test.ts@@ -153,6 +153,9 @@ describe('which machines take a teammate\'s project', () => {expect(teamWorkRefusal(offline, NOW)).toEqual({ code: 'MACHINE_OFFLINE',reason: 'MacBook Pro is offline, so it cannot show that its Harness Team account is private.' })}+ // A Mac's team account has its Mac's name, and the Mac may be online: the account is what is offline (third VM run).+ expect(teamWorkRefusal({ ...pool(), hostMachineId: 'mac' }, NOW, true)).toEqual({ code: 'MACHINE_OFFLINE',+ reason: 'The Harness Team account on MacBook Pro is offline, so it cannot show that it is private.' })})})@@ -391,6 +394,21 @@ describe('one machine: a Mac and its Harness Team account', () => {expect(f.state.starts![1]!.request).toMatchObject({ machineId: 'mate-team', cwd: '/team-swarm/lead' })})+ it('once the team account is removed, its pool left behind takes nothing: the Mac is a Mac without one again', () => {+ // Its machine is deleted, so the store no longer lists it among the tab's team machines.+ const f = oneMachine(), group = f.group()+ f.machine('mate-team').observation = reading('team', PASSED, NOW - 60_000)+ delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED+ f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, { ...f.pooled('mate-mac'), teamMachines: [] })+ expect(f.state.starts![0]!.request).toMatchObject({ machineId: 'mate-mac', cwd: '/swarm/lead' })+ process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1'+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, { ...f.pooled('mate-mac'), teamMachines: [] }))?.code)+ .toBe('TEAM_ACCOUNT_REQUIRED')+ // While it is still an account row, it is the account that runs teammates' work, offline or not.+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, { ...f.pooled('mate-mac'), teamMachines: ['mate-team'] }))?.code)+ .toBe('MACHINE_OFFLINE')+ })+it('is refused with the team account\'s own reason, and never falls back to the Mac\'s owner', () => {const f = oneMachine(), group = f.group()f.machine('mate-team').observation = reading('team', FAILED)diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 395b93660..99e1c0ce0 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -681,6 +681,20 @@ describe('GitHub App tokens through the service', () => {expect(call.mock.calls.length).toBe(calls)})+ it('runs a team daemon\'s Swarm host from its first connection, and a person\'s only once it hosts Swarm work', () => {+ const quiet = { githubTokens: () => ({ start: vi.fn(), stop: vi.fn() }), teamEngines: () => ({ start: vi.fn(), stop: vi.fn() }) }+ const started = (team: boolean) => {+ const start = vi.fn()+ const service = superTabService(fakeCore({ dataDir: mkdtempSync(join(tmpdir(), 'team-wake-')) }),+ { ...quiet, team: () => team, host: () => ({ machineId: 'machine-1', start, stop: vi.fn() }) as unknown as SuperTabHost })+ service.port.connected()+ return start.mock.calls.length+ }+ // Added to a Swarm by its Mac's daemon, which does not wake it: without its host it reported no privacy check (third VM run).+ expect(started(true)).toBe(1)+ expect(started(false)).toBe(0)+ })+it('keeps the tokens fresh while connected, and stops with the service', () => {const tokens = { start: vi.fn(), stop: vi.fn() }const engines = { start: vi.fn(), stop: vi.fn() }diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 02e1e875f..0ee430fd2 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -1,5 +1,6 @@import { readCapabilities } from './capacity.js'import { existsSync } from 'node:fs'+import { readAuthSession } from '../lib/authSession.js'import { createHash } from 'node:crypto'import type { CoreApi, ServiceRequests, SuperTabsPort } from '../core/api.js'import { backend, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError, type SuperTabHostOptions } from './host.js'@@ -156,6 +157,8 @@ export interface SuperTabServiceOptions {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'>>+ /** Whether this daemon runs team work only (a Harness Team account, `harness team on`), for a spec. */+ team?: () => boolean}export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {const preparations = new ContributionPreparations(input => (options.prepareContribution ?? prepareContribution)(core, input))@@ -197,7 +200,11 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =connected: () => {tokens.start()engines.start()- if (identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))) wake()+ // A daemon that runs team work only is there for its Swarms: its host runs from its first connection. Its Mac's daemon adds+ // a Harness Team account to a Swarm without waking it (host.ts joinTeams), and a host that never ran reports no privacy+ // check, so the Swarm read the account as offline and never sent it a teammate's work (third VM run).+ if (identifier(core.daemon.machineId()) && (existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))+ || (options.team ?? (() => readAuthSession()?.kind === 'team'))())) wake()},disconnected: disconnect,stop: disconnect,diff --git a/cli/src/superTabs/swarmGrids.spec.ts b/cli/src/superTabs/swarmGrids.spec.tsindex 777314909..407ec6eec 100644--- a/cli/src/superTabs/swarmGrids.spec.ts+++ b/cli/src/superTabs/swarmGrids.spec.ts@@ -20,6 +20,15 @@ function fixture(rows: Row[], answer: (payload: Row) => Promise<unknown> = asyncconst row = (patch: Row = {}): Row => ({ tabId: 'tab1', grid: GRID, enabled: true, ready: false, members: ['[email protected]', '[email protected]', 7], ...patch })describe('the owner\'s Swarm grids', () => {+ it('are not asked for by a daemon that runs team work only', async () => {+ const f = fixture([row()])+ const team = new SwarmGrids(fakeCore({ dataDir: '/isolated-grid-fixture' }), 'host', { backend: f.backend, open: f.open, now: () => 1_000,+ newId: () => 'id', team: () => true } as never)+ await team.tick()+ expect(f.backend).not.toHaveBeenCalled()+ expect(f.open).not.toHaveBeenCalled()+ })+it('brings a turned-on Swarm\'s grid to its people and tells the Swarm, then leaves it alone until something changes', async () => {const f = fixture([row()])await f.grids.tick()diff --git a/cli/src/superTabs/swarmGrids.ts b/cli/src/superTabs/swarmGrids.tsindex 08792779f..726fc7e3e 100644--- a/cli/src/superTabs/swarmGrids.ts+++ b/cli/src/superTabs/swarmGrids.ts@@ -10,11 +10,14 @@ import { randomUUID } from 'node:crypto'import type { CoreApi } from '../core/api.js'import { openDaemon } from '../agentClient/daemon.js'import { backend, identifier, object, SuperTabHostError } from './host.js'+import { readAuthSession } from '../lib/authSession.js'/** How often the owner's Swarms are read. */export const GRID_POLL_MS = 60_000-interface Deps { backend: typeof backend; open: typeof openDaemon; now: () => number; newId: () => string }+interface Deps { backend: typeof backend; open: typeof openDaemon; now: () => number; newId: () => string+ /** Whether this daemon runs team work only (a Harness Team account, `harness team on`): it keeps no Swarm's grid. */+ team?: () => boolean }export class SwarmGrids {private next = 0@@ -31,6 +34,9 @@ export class SwarmGrids {}private async pass(): Promise<void> {+ // The owner's computer keeps the owner's Swarms' grids. A team sign-in may not read them, and asking every minute only+ // filled its log with the refusal (third VM run).+ if ((this.deps.team ?? (() => readAuthSession()?.kind === 'team'))()) return// A backend before the add-on reads `grids` as a Swarm id and answers 404: it has no grids to keep.const listed = await this.deps.backend(this.core, 'GET', '/api/super-tabs/grids').catch((error: unknown) => {if (error instanceof SuperTabHostError && error.status === 404) return []diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsindex 4cc35041b..938b17870 100644--- a/cli/src/team/command.spec.ts+++ b/cli/src/team/command.spec.ts@@ -39,6 +39,7 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTypconst post = vi.fn(async (path: string, _body: unknown, _headers?: Record<string, string>): Promise<unknown> => {if (path === '/api/auth/handoff') return { code: CODE, expiresIn: 90 }if (path === '/api/auth/handoff/redeem') return { token: 'hna_team', refreshToken: 'hnr_team', expiresIn: 3600, kind: 'team' }+ if (path === '/api/machines/resolve-computer') return { machine: { machineId: 'm-team' }, created: true }return {}})const deps: TeamCommandDeps = {@@ -508,6 +509,12 @@ describe('internal verbs', () => {expect(f.deps.takeHandoff).toHaveBeenCalledWith('/Users/harnessteam/.harness/team-handoff')expect(f.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: 't'.repeat(32) })expect(f.session()).toMatchObject({ kind: 'team', computerId: 't'.repeat(32), refreshToken: 'hnr_team' })+ // Its machine, before its daemon starts: launchd runs the master directly, and `harness start` would have resolved it.+ expect(f.post.mock.calls.map(([path]) => path)).toEqual(['/api/auth/handoff/redeem', '/api/machines/resolve-computer'])+ expect(f.post).toHaveBeenLastCalledWith('/api/machines/resolve-computer', { computerId: 't'.repeat(32), label: 'Mac-placeholder · Team' },+ { authorization: 'Bearer x' })+ expect(f.session()).toMatchObject({ kind: 'team', machineId: 'm-team', refreshToken: 'hnr_team' })+ expect(f.out.join('\n')).toContain('[team] runs as machine m-team')expect(f.status.get(STATUS)).toMatchObject({ signIn: { state: 'signed-in' }, privacy: { passed: true },engines: { claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: true } } })expect(f.deps.engines).toHaveBeenCalledWith(config)@@ -536,12 +543,51 @@ describe('internal verbs', () => {expect(unsafe.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed', detail: 'not this account\'s private file' })})- it('__start leaves an existing sign-in alone, runs the check with no code, and writes nothing outside the team account', async () => {+ it('__start records the machine of a team sign-in that has none, once, and starts the daemon when it cannot', async () => {+ // A team account set up before this: signed in, but its daemon ran as its computer id (third VM run).+ const older = inTeam({ takeHandoff: () => null })+ older.setSession({ ...computer, kind: 'team', refreshToken: 'htr_old', machineId: undefined })+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], older.deps)).toBe(0)+ expect(older.post).toHaveBeenCalledWith('/api/machines/resolve-computer', { computerId: 'c'.repeat(32), label: 'Mac-placeholder · Team' },+ { authorization: 'Bearer x' })+ expect(older.session()).toMatchObject({ kind: 'team', machineId: 'm-team', refreshToken: 'htr_old' })+ older.post.mockClear()+ await teamCommand(['__start'], older.deps)+ expect(older.post).not.toHaveBeenCalled()+ const offline = inTeam({ takeHandoff: () => null, post: (async () => { throw new Error('connect ECONNREFUSED') }) as never })+ offline.setSession({ ...computer, kind: 'team', machineId: undefined })+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], offline.deps)).toBe(0)+ expect(offline.session()?.machineId).toBeUndefined()+ expect(offline.out.join('\n')).toContain('could not look up this account\'s machine yet (connect ECONNREFUSED)')+ expect(offline.status.get(STATUS)).toMatchObject({ privacy: { passed: true } })+ // Only a team sign-in: the owner's own computer resolves its machine with `harness start`.+ const owner = fake({ readConfig: () => config, takeHandoff: () => null })+ owner.setSession({ ...computer, machineId: undefined })+ await teamCommand(['__start'], owner.deps)+ expect(owner.post).not.toHaveBeenCalled()+ })++ it('__start replaces a sign-in with a handed-over code (setup --sign-in-again), and keeps it when the code is refused', async () => {const signed = inTeam()- signed.setSession({ ...computer, kind: 'team' })+ signed.setSession({ ...computer, kind: 'team', refreshToken: 'htr_old' })await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], signed.deps)- expect(signed.post).not.toHaveBeenCalled()- expect(signed.out.join('\n')).toContain('was not used')+ expect(signed.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: 't'.repeat(32) })+ expect(signed.session()).toMatchObject({ kind: 'team', refreshToken: 'hnr_team' })+ expect(signed.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'htr_old' })+ expect(signed.out.join('\n')).toContain('signed in for team work again; the previous sign-in was ended')+ expect(signed.status.get(STATUS)?.signIn).toMatchObject({ state: 'signed-in' })+ const refused = inTeam({ post: (async (path: string) => {+ if (path === '/api/auth/handoff/redeem') throw Object.assign(new Error('expired'), { status: 401 })+ return {}+ }) as never })+ refused.setSession({ ...computer, kind: 'team', refreshToken: 'htr_old' })+ await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], refused.deps)+ expect(refused.session()).toMatchObject({ kind: 'team', refreshToken: 'htr_old', machineId: 'm1' })+ expect(refused.out.join('\n')).toContain('the previous sign-in is kept')+ expect(refused.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed' })+ })++ it('__start runs the check with no code, and writes nothing outside the team account', async () => {const failing = inTeam({ takeHandoff: () => null, privacy: () => ({ passed: false, item: 'ssh', detail: 'could read ~/.ssh', checkedAt: 1 }) })await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], failing.deps)expect(failing.out.join('\n')).toContain('privacy check FAILED (ssh)')diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsindex ab6823d7c..dbe38b3ea 100644--- a/cli/src/team/command.ts+++ b/cli/src/team/command.ts@@ -488,6 +488,33 @@ async function handoff(deps: TeamCommandDeps): Promise<number> {return 0}+/**+ * The team account's machine id, in its session file, before its daemon starts. `harness start` resolves a session's machine+ * (cli.ts `resolveMachineIfUnknown`), but launchd runs this account's master directly, so without this its daemon ran as its+ * computer id: its gateway counted it signed out and never put its key on the device key log, so its Mac's daemon could not+ * reach it to add it to a Swarm, and its Swarm host polled under an id that is not its machine (third VM run,+ * docs/plans/2026-10-24-swarm-team-account.md). The first resolve creates its machine, named "<this Mac> · Team".+ * Never fails the start: the next start tries again.+ */+async function recordTeamMachine(deps: TeamCommandDeps, label: string, log: (line: string) => void): Promise<void> {+ const session = deps.session()+ if (session?.kind !== 'team' || session.machineId) return+ try {+ const { headers } = await deps.auth()+ const answer = await deps.post<{ machine?: { machineId?: unknown } }>('/api/machines/resolve-computer',+ { computerId: session.computerId, label }, headers)+ const machineId = answer?.machine?.machineId+ if (typeof machineId !== 'string' || !machineId) throw new Error('Harness answered without a machine id')+ // A refresh may have rewritten the session meanwhile: the machine id goes into the newest one.+ const latest = deps.session()+ if (latest?.kind !== 'team' || latest.computerId !== session.computerId) return+ if (latest.machineId !== machineId) deps.writeSession({ ...latest, machineId, updatedAt: deps.now() })+ log(`runs as machine ${machineId}`)+ } catch (error) {+ log(`could not look up this account's machine yet (${(error as Error).message}); the next start tries again`)+ }+}+/*** `team __start <file>`: run by the team daemon's job, as the team account, before its master starts. Its lines go* to the daemon's log. Always exits 0: the daemon starts either way, signed out if the sign-in failed, and reports@@ -502,6 +529,7 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promisif (!mine) returntry { deps.writeStatus(statusFile, update) } catch (error) { log(`could not write ${statusFile}: ${(error as Error).message}`) }}+ const label = `${deps.hostname().slice(0, 60)} · Team`if (file) {let code: string | null = nulltry {@@ -510,23 +538,24 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promislog((error as Error).message)report({ signIn: { state: 'failed', at: deps.now(), detail: (error as Error).message } })}- if (code && deps.session()) {- log('already signed in; the handed-over sign-in code was not used')- report({ signIn: { state: 'signed-in', at: deps.now() } })- } else if (code) {- const label = `${deps.hostname().slice(0, 60)} · Team`+ // Setup hands a code over only when this account has no sign-in, or when its owner asked for a new one+ // (`--sign-in-again`): a sign-in already here is replaced, and kept when the new one cannot be had.+ if (code) {+ const previous = deps.session()try {const computerId = deps.computerId()const tokens = await redeemTeamHandoff(code, label, computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })deps.writeSession(teamSession(tokens, computerId, deps.autonomousEnv, deps.now()))- log('signed in for team work')+ if (previous) await revokeHarnessRefresh(deps.post, previous.refreshToken)+ log(previous ? 'signed in for team work again; the previous sign-in was ended' : 'signed in for team work')report({ signIn: { state: 'signed-in', at: deps.now() } })} catch (error) {- log(`sign-in failed: ${(error as Error).message}`)+ log(`sign-in failed: ${(error as Error).message}${previous ? '; the previous sign-in is kept' : ''}`)report({ signIn: { state: 'failed', at: deps.now(), detail: (error as Error).message } })}}}+ await recordTeamMachine(deps, label, log)if (mine) {const privacy = deps.privacy(mine)log(privacy.passed ? 'privacy check passed' : `privacy check FAILED (${privacy.item}): ${privacy.detail}`)diff --git a/docs/plans/2026-10-24-swarm-team-account.md b/docs/plans/2026-10-24-swarm-team-account.mdindex 96fd6335e..6b6fbbe53 100644--- a/docs/plans/2026-10-24-swarm-team-account.md+++ b/docs/plans/2026-10-24-swarm-team-account.md@@ -214,3 +214,42 @@ Three bugs found here were fixed and checked again in the VM. The team computer**Not exercised.** Removal through the prompt with the deletion allowed (macOS 26 has no way). `harness team remove` from a terminal other than Terminal.app, or inside a Harness pane, where the responsible process is the daemon's Node. A real owner sign-in, production minting, redeeming and machine deletion: the stand-ins answered, so the team session ending with its machine rests on #1691's backend tests. Desktop's automatic setup. A team account made by the first version, repaired to get a password. The guest helper's install: its parsing fix has a spec only. In the VM image `admin` has passwordless sudo; that file was moved aside to see sudo's prompt, then put back. Rig: tart's VNC server crashed the VM five times on connect; `vmn-start` brought it back each time.Tests: `npx vitest run src/team src/lib/guestHelperInstall.spec.ts src/superTabs/machines.spec.ts src/superTabs/service.spec.ts src/services/guestLaunches.spec.ts src/services/sharedMachines.spec.ts src/cliCommand.spec.ts src/architecture.spec.ts`: 318 passed. `npm run typecheck` is clean. No coverage gate covers `src/team` or `src/lib/guestHelperInstall.ts`.++## Validation, third VM run (24 Oct 2026)++`main` at #1702, end to end in a fresh VM from the same image (macOS 26.6.2), against a disposable backend: current `main`'s backend on the host, its own MongoDB and Redis, and a fixture identity service with two people, the owner and a teammate. The VM had the Command Line Tools installed (a Swarm start needs git). The CLI was bundled from `main` and installed by the real installer. Unlike the first two runs, nothing was a stand-in for Harness: the owner signed in with `harness login --code`, approved through the backend by the owner, so setup minted and redeemed real team codes. The teammate's machine and Lead were recorded through the API, and the owner's second and third computers were isolated daemons on the host. Engines were installed but not signed in; to probe from an agent's shell, the team account's `codex` launcher was replaced by an interactive shell. The backend ran first without a GitHub App, then with a fake one (`api.github.com` answered locally) and a public repository.++| Scenario | Result |+|---|---|+| Regular Mac, nothing set up | ✓ startup offer `not-shared`, no `harness team` line in `--help`, no shared folder or account |+| Contribute → prompt, Cancel | ✓ nothing changed, `team-setup.json` `declined`, later `startup` and `join` offers answer `declined` with no prompt |+| `harness team setup`, accept | ✓ Users & Groups lists "Harness Team · Standard", home 700, `Private ✓`, `hta_` session, machine row `team` with the Mac as `hostMachineId`. ✗ never joined the Swarm (bugs 8, 9) |+| Teammate's project on the Mac | ✓ (after working around 8 and 9) uid 600 in `/Users/harnessteam/harnesses/worktrees/…`; from its shell the owner's home, `~/code`, `~/.gitconfig`, `~/.ssh` and `Library/Keychains` all `Permission denied`. The owner's own project ran as `admin` |+| Team session limits, real token | ✓ 403 `TEAM_SESSION_LIMITED` for the machine list, another machine's host routes, handoff (viewer and team), settings, routing policy, contribute, pause and delete; the web relay closes `4403` on `machine_select` |+| Privacy check fails | ✓ home 750: within 80 s the pool reads `PRIVACY_CHECK_FAILED (sentinel)`, starts naming the Mac or the team machine are refused, nothing runs as the owner. 700 again: passes at the next 5-minute check |+| Team daemon offline | ✓ `MACHINE_OFFLINE` about 40 s after `bootout`; the owner's own start still ran as the owner; back 4 s after `bootstrap` |+| Switch | ✓ unset: a regular machine of the owner admits a teammate's start. `=1`: that machine refuses `TEAM_ACCOUNT_REQUIRED`, the Mac's team account still takes it |+| Repair | ✓ repair prompt; same uid, password hash, plist and session. ✗ `--sign-in-again` kept the old sign-in (bug 10) |+| Roster sync | ✓ the owner's VM and host daemons pin each other, both write `team-machines.json` with the team machine, background sessions run only between the owner's own machines |+| Removal | ✓ through the prompt: refused, nothing changed, daemon running. ✓ in Terminal with Allow: everything local gone, home 700. ✗ the team machine stays on the account and its session stays live when the owner signed in by QR (open 12); ✗ the old pools stay in the Swarm (open 13) |+| `team on` / `off` | ✓ same computer and machine id, `team` then `computer` again after `harness login`; the host daemons' `team-machines.json` added it, then forgot it |+| Reboot, backend restart | ✓ the LaunchDaemon comes back at boot and checks again; both daemons reconnect after a backend restart |++**GitHub App.** Without the App, every teammate start on a Team machine fails at once with "This Harness server has no GitHub App, and a Harness Team account has no git login of its own, so it cannot fetch the project." That holds for a project without a repository too (`projectFolder.ts` asks for a token before anything else). With the switch unset, regular machines still take teammates' work as their owners. So no teammate's work can run in a Harness Team account until the server has the App.++**Fixed in this change** (each with a spec that fails on `main`):+8. *The team daemon ran as its computer id.* `harness start` writes a session's machine id; launchd runs the team daemon's master directly, so its session never had one. Its gateway counted it signed out, so its key never reached the device key log, its Mac's daemon could not reach it (`Could not add this Mac's Harness Team account to its Swarm: That machine is not linked to this one`, retried with backoff forever), and its host would have polled under an id that is not a machine. `team __start` now resolves the machine before the daemon starts, which also names it "<Mac> · Team" in app-wide lists (it carried the Mac's bare hostname, so `harness machines` showed two identical rows).+9. *The team account's Swarm host never started.* The Mac's daemon adds it to a Swarm without waking it, and a host wakes on connect only with a journal, which only a wake writes. The pool stayed `MACHINE_OFFLINE`. A team daemon's host now runs from its first connection.+10. *`--sign-in-again` did nothing.* `team __start` ignored a handed-over code when a session existed, yet setup printed `✓ The Harness Team account is signed in.` It now redeems it, ends the previous session, and keeps it when the code is refused.+11. *Smaller.* A team daemon asked for the owner's Swarm grids every minute and logged the refusal; it no longer asks. A Mac's offline team account was reported as "<Mac> is offline" while the Mac was online; it now says the Harness Team account on that Mac is offline.++Checked again in the VM with a bundle of this branch: a fresh setup signed in with a machine id, registered its key, was added to the Swarm by the Mac's daemon, woke its host, passed its check and took a teammate's start in the team account with no step by hand; `--sign-in-again` ended the previous session.++**Open, for a decision:**+12. *Removal leaves the team machine and its session when the owner signed in by QR.* `harness team remove` prints `! Its computer is still on your Harness account (Billing needs your Autonomous sign-in…)`: `DELETE /api/machines/:id` refuses every Harness-issued token before it looks at the machine, though `machineService.destroy` needs one only for a billed machine. The team session stayed refreshable until the machine was deleted with an Autonomous sign-in. Its tokens were deleted with the home, so nothing holds them. The fix is in the shared route (ask for the Autonomous token only for a billed machine), so it is not in this change.+13. *Removal leaves the team pools in the Swarm.* Even with the machine deleted, the Mac keeps its old team pools, so a teammate's start on the Mac is refused `MACHINE_OFFLINE` instead of running as before (switch unset) or `TEAM_ACCOUNT_REQUIRED` (switch on). Options: `harness team remove` also removes the pools of the account it deleted, or routing skips a team pool whose machine is no longer a team machine.+14. Signing the Mac out of Harness, or into another account, leaves the team account signed in to the previous account and taking its Swarm's work. `--sign-in-again` (bug 10) moves it to the current account.++**Rig notes.** tart's VNC server crashed the VM four times, twice with no client of ours connected; the VM ran without VNC except to answer a prompt. Each power-off doubled as a reboot test. Over VNC, shifted characters type unshifted.++Tests: `npx vitest run src/team src/superTabs src/lib/e2ee/machineKinds.spec.ts src/architecture.spec.ts src/cliCommand.spec.ts` (CLI, 936 passed) and `npx vitest run src/superTabs src/lib/teamSession` (backend, 417 passed). `npm run typecheck` is clean in both.