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` against fake deps: no administrator prompt, account, launchd, daemon or backend is touched.
*/
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 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'
const OWNER_HOME = '/Users/owner-placeholder'
const CODE = `hnh_${'b'.repeat(43)}`
const STATUS = '/Library/Application Support/Harness/Team/status.json'
const computer: AuthSession = { version: 1, accessToken: 'access-placeholder', refreshToken: 'hnr_old', autonomousEnv: 'prod', computerId: 'c'.repeat(32), machineId: 'm1', updatedAt: 1 }
const config: TeamConfig = {
version: 1, user: 'harnessteam', realName: 'Harness Team', home: '/Users/harnessteam', owner: 'owner-placeholder', ownerHome: OWNER_HOME,
sentinel: `${OWNER_HOME}/.harness-team-privacy`, port: 18493, label: 'ai.autonomous.harness.team',
plist: '/Library/LaunchDaemons/ai.autonomous.harness.team.plist', statusFile: STATUS,
node: '/Users/harnessteam/.harness/runtime/node-v1/bin/node', cli: '/Users/harnessteam/.harness/cli/cli.js', env: {}, createdAt: 'x',
}
function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnType<RunAdmin>>; statusAfter?: (startedAt: number) => TeamStatus | null; stage?: string } = {}) {
let now = 1_000_000
let session: AuthSession | null = computer
const out: string[] = [], err: string[] = []
const built: AdminScript[] = []
const prompts: string[] = []
const vias: Array<string | undefined> = []
const status = new Map<string, TeamStatus>()
const admin = vi.fn<RunAdmin>(async (build, prompt, via) => {
built.push(build(over.stage ?? '/private/var/folders/aa/T/harness-team-stage'))
prompts.push(prompt)
vias.push(via)
return over.adminResult ?? { ok: true, stdout: 'harness: handed a sign-in to the team account\n' }
})
const startedAt = now
const 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 = {
platform: 'darwin',
out: (line) => out.push(line), err: (line) => err.push(line),
user: () => 'owner-placeholder', home: () => OWNER_HOME, uid: () => 501, hostname: () => 'Mac-placeholder',
env: {}, interactive: false, ask: vi.fn(async () => 'y'), now: () => now, sleep: vi.fn(async (ms: number) => { now += ms }),
session: () => session, writeSession: vi.fn((s: AuthSession) => { session = s }),
updateSession: vi.fn(async (change: (latest: AuthSession) => AuthSession | null) => {
const next = session ? change(session) : null
if (next) session = next
return next ?? session
}), signOutAsked: (flags) => signOutAsked({ interactive: over.interactive ?? false, flags, ancestors: () => [], isApp: () => false }),
removeSignIn: vi.fn(() => { session = null }),
auth: vi.fn(async () => ({ session: session!, headers: { authorization: 'Bearer x' } })), post: post as never,
get: vi.fn(async (path: string) => path === '/api/machines' ? { machines: MACHINES } : { user: { id: 'user-placeholder-1' } }) as never,
delete: vi.fn(async () => ({ deleted: true })) as never, machineKey: () => ({ priv: new Uint8Array(32).fill(9) }),
computerId: () => 't'.repeat(32), autonomousEnv: 'prod',
installed: () => ({ cliDir: `${OWNER_HOME}/.harness/cli`, cliJs: `${OWNER_HOME}/.harness/cli/cli.js`,
node: `${OWNER_HOME}/.harness/runtime/node-v1/bin/node`, nodeRuntimeDir: `${OWNER_HOME}/.harness/runtime/node-v1`, tmuxRuntimeDir: null }),
exists: () => true, mode: () => 0o700, admin,
readConfig: () => null,
readStatus: (path) => over.statusAfter ? over.statusAfter(startedAt) : status.get(path) ?? null,
writeStatus: vi.fn((path: string, update: Partial<TeamStatus>) => { status.set(path, { ...(status.get(path) ?? { version: 1 }), ...update, version: 1 }) }),
accountExists: vi.fn(async () => false), jobState: vi.fn(async () => ({ loaded: true, pid: 4242, state: 'running' })),
takeHandoff: vi.fn(() => CODE), privacy: vi.fn((): PrivacyResult => ({ passed: true, checkedAt: now })),
engines: vi.fn(async (): Promise<TeamEngines> => ({ checkedAt: now, claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: true } })),
stopDaemon: vi.fn(async () => true), startDaemon: vi.fn(async () => {}),
...over,
}
return { deps, out, err, built, prompts, vias, post, admin, status, session: () => session, setSession: (s: AuthSession | null) => { session = s } }
}
/** The owner's machines as the backend lists them, computer ids lower case without dashes: this computer, the team
* account's, and a dedicated Mac mini's. */
const TEAM_COMPUTER = 'ebe7fc88-cd44-491f-aa61-9963fa0dfd82'
const MACHINES = [
{ machineId: 'm1', computerId: 'c'.repeat(32), sessionKind: 'computer' },
{ machineId: 'm-team', computerId: TEAM_COMPUTER.replace(/-/g, ''), sessionKind: 'team', hostMachineId: 'm1' },
{ machineId: 'm-mini', computerId: 'a'.repeat(32), sessionKind: 'team' },
{ machineId: 'm-other-mac-team', computerId: 'b'.repeat(32), sessionKind: 'team', hostMachineId: 'm-other-mac' },
]
const reported = (startedAt: number): TeamStatus => ({ version: 1, signIn: { state: 'signed-in', at: startedAt + 3_000 }, privacy: { passed: true, checkedAt: startedAt + 3_000 } })
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 <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('refuses before any prompt, in words and in JSON: Swarm v3 has no Team accounts (#4221)', async () => {
const f = fake({ statusAfter: reported })
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.
})
describe('harness team status', () => {
it('lists the account, the daemon, the sign-in, the privacy check and everything setup made', async () => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
f.status.set(STATUS, { version: 1, signIn: { state: 'signed-in', at: 1_000_000 - 30_000 }, privacy: { passed: true, checkedAt: 1_000_000 - 120_000 } })
expect(await teamCommand(['status'], f.deps)).toBe(0)
const text = f.out.join('\n')
for (const needle of ['Harness Team (harnessteam)', '● exists', '● running (pid 4242)', '✓ signed in (30s ago)', 'Private ✓ (checked 2m ago)',
`${OWNER_HOME} · mode 700 ✓`, '/Users/harnessteam', 'ai.autonomous.harness.team, a LaunchDaemon at /Library/LaunchDaemons/ai.autonomous.harness.team.plist',
'/Library/Application Support/Harness/team.json', 'sudo dscl . -delete /Users/harnessteam', 'harness team remove']) {
expect(text, needle).toContain(needle)
}
})
// Task #2264: an account held by data not deleted yet said so nowhere a person looks.
it('says when the data of ended sessions is not deleted yet, and nothing when none is waiting', async () => {
const said = async (purges?: { pending: number; unreadable: boolean; at: number }) => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
f.status.set(STATUS, { version: 1, ...(purges ? { purges } : {}) })
await teamCommand(['status'], f.deps)
return f.out.join('\n')
}
const two = await said({ pending: 2, unreadable: false, at: 1_000_000 - 60_000 })
expect(two).toContain('purges ◍ 2 ended sessions\' data not deleted yet (checked 60s ago)')
expect(two).toContain('this account takes no other project\'s work until it has')
expect(await said({ pending: 1, unreadable: false, at: 1_000_000 })).toContain('◍ 1 ended session\'s data not deleted yet')
const unreadable = await said({ pending: 0, unreadable: true, at: 1_000_000 })
expect(unreadable).toContain('purges ✗ the record of what is still to delete can\'t be read')
expect(unreadable).toContain('the Team daemon\'s log says where it was kept')
expect(await said({ pending: 0, unreadable: false, at: 1_000_000 })).not.toContain('purges ')
expect(await said()).not.toContain('purges ')
const json = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
json.status.set(STATUS, { version: 1, purges: { pending: 2, unreadable: false, at: 5 } })
await teamCommand(['status', '--json'], json.deps)
expect(JSON.parse(json.out[0]!).purges).toEqual({ pending: 2, unreadable: false, at: 5 })
})
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')
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)
expect(JSON.parse(json.out[0]!).engines).toEqual({ checkedAt: 5, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true } })
})
it('on Linux, a home whose group bits are an ACL mask (a guest\'s entry) is private when the check passed', async () => {
// setfacl -n keeps the mask a guest's `u:<guest>:x` needs, and `stat` then shows the mask as the group bits (710).
const shown = async (mode: number, passed: boolean) => {
const f = fake({ platform: 'linux', readConfig: () => config, accountExists: vi.fn(async () => true), mode: () => mode })
f.status.set(STATUS, { version: 1, privacy: passed
? { passed: true, checkedAt: 1_000_000 - 60_000 }
: { passed: false, item: 'home-listing', detail: 'The team account could list it.', checkedAt: 1_000_000 - 60_000 } })
await teamCommand(['status'], f.deps)
return f.out.join('\n')
}
expect(await shown(0o710, true)).toContain('mode 710 ✓')
expect(await shown(0o710, false)).toContain('mode 710 ✗')
expect(await shown(0o715, true)).toContain('mode 715 ✗')
expect(await shown(0o700, true)).toContain('mode 700 ✓')
})
it('shows what is wrong: a failed check, an open home, a stopped daemon', async () => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true), mode: () => 0o750,
jobState: vi.fn(async () => ({ loaded: false, pid: null, state: null })), exists: (p) => p !== config.plist })
f.status.set(STATUS, { version: 1, privacy: { passed: false, item: 'sentinel', detail: 'The team account could read it.', checkedAt: 1_000_000 - 7_200_000 } })
await teamCommand(['status'], f.deps)
const text = f.out.join('\n')
expect(text).toContain('○ not installed')
expect(text).toContain('? not reported yet')
expect(text).toContain('✗ sentinel: The team account could read it. (checked 2h ago)')
expect(text).toContain('mode 750 ✗ should be 700')
})
it('shows the owner\'s agents\' private temporary folder, and says when it is not private', async () => {
const line = async (state: 'private' | 'open' | 'not-made', mode: number | null) => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true), agentTmp: () => ({ path: `${OWNER_HOME}/.harness/agent-tmp`, state, mode }) })
await teamCommand(['status'], f.deps)
return f.out.join('\n').split('\n').find(text => text.startsWith(' temp files'))
}
expect(await line('private', 0o700)).toBe(` temp files ${OWNER_HOME}/.harness/agent-tmp · mode 700 ✓`)
expect(await line('open', 0o755)).toContain('mode 755 ✗')
expect(await line('open', null)).toContain('✗')
expect(await line('not-made', null)).toContain('made when your next agent starts')
const json = fake({ readConfig: () => config, accountExists: vi.fn(async () => true), agentTmp: () => ({ path: '/p', state: 'private', mode: 0o700 }) })
await teamCommand(['status', '--json'], json.deps)
expect(JSON.parse(json.out[0]!).agentTmp).toEqual({ path: '/p', state: 'private', mode: '700' })
})
it('answers in JSON, and says plainly when there is no team account or the computer is dedicated', async () => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
await teamCommand(['status', '--json'], f.deps)
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.')
const linux = fake({ platform: 'linux', session: () => ({ ...computer, kind: 'team' }) })
await teamCommand(['status'], linux.deps)
expect(linux.out[0]).toContain('runs team work only')
const linuxJson = fake({ platform: 'linux' })
await teamCommand(['status', '--json'], linuxJson.deps)
expect(JSON.parse(linuxJson.out[0]!)).toEqual({ account: false, dedicated: false })
})
})
describe('harness team remove', () => {
const removed = { ok: true as const, stdout: `harness: deleted the account harnessteam\nharness: team computer ${TEAM_COMPUTER}\nharness: removed the Harness Team account, its home folder and its daemon\n` }
const refused = { ok: false as const, code: 'FAILED' as const, status: 9,
message: 'could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). Nothing was removed: the Harness Team account and its daemon run as before' }
it('runs one privileged removal with what the config names, behind the prompt when not in a terminal', async () => {
const f = fake({ readConfig: () => ({ ...config, env: { AUTONOMOUS_ENV: 'stag' } }), adminResult: removed })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.prompts[0]).toContain('remove the Harness Team account')
expect(f.vias[0]).toBe('prompt')
expect(f.built[0]!.script).toContain("TEAM_HOME='/Users/harnessteam'")
expect(f.built[0]!.script).toContain(`SENTINEL='${OWNER_HOME}/.harness-team-privacy'`)
expect(f.out.join('\n')).toContain('Your home folder stays private')
})
it('in a terminal, runs it with sudo there, so macOS can ask to let the terminal administer the Mac', async () => {
const f = fake({ readConfig: () => config, interactive: true, adminResult: removed })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.vias[0]).toBe('sudo')
expect(f.out[0]).toContain('sudo asks for your password here; macOS may then ask to let this terminal administer your computer')
const cancelled = fake({ readConfig: () => config, interactive: true, adminResult: { ok: false, code: 'CANCELLED', message: '' } })
expect(await teamCommand(['remove'], cancelled.deps)).toBe(1)
expect(cancelled.err[0]).toBe('✗ Nothing was removed: sudo did not get an administrator password.')
})
it('takes this computer\'s team machine off the owner\'s account once the account is gone, which signs it out', async () => {
const f = fake({ readConfig: () => config, adminResult: removed })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
// Only the team machine the backend says lives on this computer: not this computer's own, not any other team machine.
expect(f.deps.delete).toHaveBeenCalledTimes(1)
expect(f.deps.delete).toHaveBeenCalledWith('/api/machines/m-team', { authorization: 'Bearer x' })
expect(f.out.join('\n')).toContain('✓ Took its computer off your Harness account, which signs it out.')
expect(f.post).not.toHaveBeenCalled()
const json = fake({ readConfig: () => config, adminResult: removed })
await teamCommand(['remove', '--json'], json.deps)
expect(JSON.parse(json.out.at(-1)!)).toEqual({ ok: true, removed: true, computer: { removed: 1 } })
})
// Audit L3: the id came from a file the Team account wrote, so a Team agent could name the owner's team machine on another Mac.
it('ignores a computer id the Team account wrote: another Mac\'s team machine stays', async () => {
for (const named of ['b'.repeat(32), 'a'.repeat(32), 'c'.repeat(32)]) {
const f = fake({ readConfig: () => config, adminResult: { ok: true, stdout: `harness: team computer ${named}\n` } })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.deps.delete).toHaveBeenCalledTimes(1)
expect(f.deps.delete).toHaveBeenCalledWith('/api/machines/m-team', { authorization: 'Bearer x' })
}
})
it('still takes it off when the Team account deleted or emptied its id file', async () => {
const f = fake({ readConfig: () => config, adminResult: { ok: true, stdout: 'harness: removed the Harness Team account, its home folder and its daemon\n' } })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.deps.delete).toHaveBeenCalledWith('/api/machines/m-team', { authorization: 'Bearer x' })
})
it('takes nothing off, and says what to do, when the backend links no team machine to this computer', async () => {
const elsewhere = { ...computer, machineId: 'm-no-team' }
const f = fake({ readConfig: () => config, adminResult: removed, session: () => elsewhere, auth: vi.fn(async () => ({ session: elsewhere, headers: { authorization: 'Bearer x' } })) })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.deps.delete).not.toHaveBeenCalled()
expect(f.out.join('\n')).toContain('If its computer, "Mac-placeholder · Team", is still on your Harness account, remove it there: harness machines')
})
it('takes nothing off when this computer has no machine id to compare with: a missing id must not match a team machine with no Mac', async () => {
const { machineId: _none, ...noMachine } = computer
const f = fake({ readConfig: () => config, adminResult: removed, session: () => noMachine, auth: vi.fn(async () => ({ session: noMachine, headers: { authorization: 'Bearer x' } })) })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.deps.delete).not.toHaveBeenCalled()
expect(f.out.join('\n')).toContain('If its computer, "Mac-placeholder · Team", is still on your Harness account, remove it there: harness machines')
})
it('says how to finish when the computer cannot be taken off: signed out here, or the backend failing', async () => {
const signedOut = fake({ readConfig: () => config, adminResult: removed, session: () => null })
expect(await teamCommand(['remove'], signedOut.deps)).toBe(0)
expect(signedOut.out.join('\n')).toContain('! Its computer is still on your Harness account (this computer is not signed in to Harness). '
+ 'Remove "Mac-placeholder · Team": harness machines')
const failing = fake({ readConfig: () => config, adminResult: removed, delete: vi.fn(async () => { throw new Error('backend unavailable') }) as never })
expect(await teamCommand(['remove'], failing.deps)).toBe(0)
expect(failing.out.join('\n')).toContain('(backend unavailable)')
})
it('when macOS keeps the account, says that nothing was removed and exactly what to do', async () => {
const f = fake({ readConfig: () => config, adminResult: refused })
expect(await teamCommand(['remove'], f.deps)).toBe(1)
const text = f.err.join('\n')
expect(f.err[0]).toBe('✗ macOS kept the Harness Team account: could not delete the account harnessteam: macOS did not allow it (eDSPermissionError). '
+ 'Nothing was removed: the Harness Team account and its daemon run as before.')
expect(text).toContain('run harness team remove in Terminal')
expect(text).toContain('macOS asks to let Terminal')
expect(text).toContain('delete "Harness Team" in System Settings > Users & Groups (ⓘ, Delete User…, Delete the home folder)')
// Nothing on the backend: the account still runs, signed in.
expect(f.deps.get).not.toHaveBeenCalled()
expect(f.deps.delete).not.toHaveBeenCalled()
expect(f.post).not.toHaveBeenCalled()
const terminal = fake({ readConfig: () => config, interactive: true, adminResult: refused, env: { __CFBundleIdentifier: 'com.apple.Terminal' } })
expect(await teamCommand(['remove'], terminal.deps)).toBe(1)
expect(terminal.err.join('\n')).toContain('it asks again after: tccutil reset SystemPolicySysAdminFiles com.apple.Terminal')
const odd = fake({ readConfig: () => config, interactive: true, adminResult: refused, env: { __CFBundleIdentifier: 'x; rm -rf ~' } })
await teamCommand(['remove'], odd.deps)
expect(odd.err.join('\n')).toContain('it asks again after: tccutil reset SystemPolicySysAdminFiles\n')
const json = fake({ readConfig: () => config, adminResult: refused })
await teamCommand(['remove', '--json'], json.deps)
expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: false, code: 'DELETE_REFUSED', next: expect.arrayContaining([expect.stringContaining('Users & Groups')]) })
})
it('on a Mac, never checks the owner\'s name: only the Linux removal needs it (for the relay folder setup made)', async () => {
// A macOS short name the account pattern does not take, with no config to name the owner: removed as it always was.
const f = fake({ user: () => 'Owner Placeholder', exists: (p) => p === '/Users/harnessteam', adminResult: removed })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.admin).toHaveBeenCalledTimes(1)
expect(f.built[0]!.script).toContain("TEAM_HOME='/Users/harnessteam'")
})
it('has nothing to do without an account, and refuses off a Mac or as root', async () => {
const none = fake({ exists: () => false })
expect(await teamCommand(['remove', '--json'], none.deps)).toBe(0)
expect(JSON.parse(none.out[0]!)).toEqual({ ok: true, removed: false })
expect(none.admin).not.toHaveBeenCalled()
expect(await teamCommand(['remove'], fake({ platform: 'win32' }).deps)).toBe(1)
expect(await teamCommand(['remove'], fake({ uid: () => 0 }).deps)).toBe(1)
const cancelled = fake({ adminResult: { ok: false, code: 'CANCELLED', message: '' } })
expect(await teamCommand(['remove'], cancelled.deps)).toBe(1)
expect(cancelled.err[0]).toBe('✗ Nothing was removed: the administrator prompt was cancelled.')
const failed = fake({ adminResult: { ok: false, code: 'FAILED', message: 'dscl refused' } })
expect(await teamCommand(['remove'], failed.deps)).toBe(1)
expect(failed.err[0]).toContain('dscl refused')
})
})
describe('harness team on and off', () => {
it('on: mints a code that converts this very computer, with its machine key\'s proof, redeems it here, and swaps the daemon onto it', async () => {
const f = fake({ platform: 'linux', now: () => 1761300000000 })
const order: string[] = []
f.post.mockImplementation(async (path: string) => {
order.push(path)
if (path === '/api/auth/handoff') return { code: CODE, expiresIn: 90, kind: 'team' }
if (path === '/api/auth/handoff/redeem') return { token: 'hta_team', refreshToken: 'htr_team', expiresIn: 3600, kind: 'team' }
return {}
})
;(f.deps.stopDaemon as ReturnType<typeof vi.fn>).mockImplementation(async () => { order.push('stop'); return true })
expect(await teamCommand(['on', '--yes'], f.deps)).toBe(0)
expect(f.post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team', computerId: 'c'.repeat(32),
proof: { machineId: 'm1', at: 1761300000000, sig: expect.any(String) } }, { authorization: 'Bearer x' })
expect(f.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: computer.computerId })
// The daemon stops before the redeem: a daemon still on the old sign-in would make this an ordinary machine again.
expect(order.slice(0, 3)).toEqual(['/api/auth/handoff', 'stop', '/api/auth/handoff/redeem'])
// The team sign-in replaces the previous one in the session file; that one is signed out where it can be.
expect(f.session()).toEqual(expect.objectContaining({ kind: 'team', accessToken: 'hta_team', refreshToken: 'htr_team', computerId: computer.computerId, machineId: 'm1' }))
expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_old' })
expect(f.out.join('\n')).toContain('previous sign-in was discarded')
expect(f.deps.startDaemon).toHaveBeenCalled()
})
it('on: an Autonomous sign-in is discarded too, and one this computer cannot prove changes nothing', async () => {
const sso: AuthSession = { ...computer, accessToken: 'eyJ.sso-placeholder', refreshToken: 'sso-refresh-placeholder' }
const f = fake({ platform: 'linux' })
f.setSession(sso)
expect(await teamCommand(['on', '--yes'], f.deps)).toBe(0)
expect(f.session()).toMatchObject({ kind: 'team', accessToken: 'hna_team' })
expect(JSON.stringify(f.session())).not.toContain('sso')
expect(f.post).not.toHaveBeenCalledWith('/api/auth/revoke', expect.anything())
const nokey = fake({ platform: 'linux', machineKey: () => null })
nokey.setSession(sso)
expect(await teamCommand(['on', '--yes'], nokey.deps)).toBe(1)
expect(nokey.err[0]).toContain('no device key yet')
expect(nokey.err[0]).toContain('Nothing was changed on this computer.')
expect(nokey.post).not.toHaveBeenCalled()
expect(nokey.deps.stopDaemon).not.toHaveBeenCalled()
expect(nokey.session()).toBe(sso)
})
it('on: a refused redeem starts the daemon again on the sign-in it had, and changes nothing', async () => {
const f = fake({ platform: 'linux' })
f.post.mockImplementation(async (path: string) => {
if (path === '/api/auth/handoff') return { code: CODE, expiresIn: 90, kind: 'team' }
throw Object.assign(new Error('That code has expired.'), { status: 401 })
})
expect(await teamCommand(['on', '--yes', '--json'], f.deps)).toBe(1)
expect(JSON.parse(f.out.at(-1)!)).toMatchObject({ ok: false, code: 'EXPIRED', message: expect.stringContaining('Nothing was changed on this computer.') })
expect(f.session()).toBe(computer)
expect(f.deps.stopDaemon).toHaveBeenCalled()
expect(f.deps.startDaemon).toHaveBeenCalled()
expect(f.deps.writeSession).not.toHaveBeenCalled()
})
it('on: asks first at a terminal, needs --yes otherwise, and leaves a Mac with a team account alone', async () => {
const ask = fake({ interactive: true, ask: vi.fn(async () => 'n') })
expect(await teamCommand(['on'], ask.deps)).toBe(1)
expect(ask.post).not.toHaveBeenCalled()
const yes = fake({ interactive: true })
expect(await teamCommand(['on'], yes.deps)).toBe(0)
expect(await teamCommand(['on'], fake().deps)).toBe(1)
const mac = fake({ readConfig: () => config })
expect(await teamCommand(['on', '--yes'], mac.deps)).toBe(1)
expect(mac.err[0]).toContain('has a Harness Team account')
expect(await teamCommand(['on', '--yes'], fake({ session: () => null }).deps)).toBe(1)
const already = fake({ session: () => ({ ...computer, kind: 'team' }) })
expect(await teamCommand(['on', '--json'], already.deps)).toBe(0)
expect(JSON.parse(already.out[0]!)).toEqual({ ok: true, changed: false })
})
it('on: changes nothing when the backend will not hand out a team sign-in, or makes something else', async () => {
const f = fake({ post: (async () => { throw Object.assign(new Error('Add a phone from a computer'), { status: 403 }) }) as never })
expect(await teamCommand(['on', '--yes'], f.deps)).toBe(1)
expect(f.session()).toBe(computer)
expect(f.deps.stopDaemon).not.toHaveBeenCalled()
expect(f.err[0]).toContain('Nothing was changed on this computer.')
// A backend from before team sessions: the redeem makes a phone's session, which is signed out again.
const old = fake()
old.post.mockImplementation(async (path: string) => path === '/api/auth/handoff' ? { code: CODE, expiresIn: 90 }
: path === '/api/auth/handoff/redeem' ? { token: 'hna_phone', refreshToken: 'hnr_phone', expiresIn: 3600 } : {})
expect(await teamCommand(['on', '--yes', '--json'], old.deps)).toBe(1)
expect(JSON.parse(old.out.at(-1)!)).toMatchObject({ ok: false, code: 'NOT_TEAM' })
expect(old.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_phone' })
expect(old.session()).toBe(computer)
// Stopped for the redeem, and started again on the sign-in it had.
expect(old.deps.startDaemon).toHaveBeenCalled()
})
// 10-27: a sign-out nobody asked for (a desktop test's `harness logout`) signed a whole Mac out. `team off`
// takes the sign-in away too, so it asks the same: a terminal, or the flag a person's button passes.
it('off with no terminal and no flag refuses, and keeps the team sign-in and its refresh token', async () => {
const f = fake()
const team = { ...computer, kind: 'team' as const, refreshToken: 'htr_team' }
f.setSession(team)
expect(await teamCommand(['off'], f.deps)).toBe(1)
expect(f.session()).toEqual(team)
expect(f.post).not.toHaveBeenCalledWith('/api/auth/revoke', expect.anything())
expect(f.deps.stopDaemon).not.toHaveBeenCalled()
expect(f.err.join('\n')).toContain('--from-sign-out-button')
})
it('off: signs the team session out, then the ordinary sign-in at a terminal, or says how', async () => {
const signIn = vi.fn(async () => {})
const f = fake({ interactive: true, signIn })
f.setSession({ ...computer, kind: 'team', refreshToken: 'htr_team' })
expect(await teamCommand(['off'], f.deps)).toBe(0)
expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'htr_team' })
expect(f.session()).toBeNull()
expect(signIn).toHaveBeenCalledWith(true)
const quiet = fake()
quiet.setSession({ ...computer, kind: 'team' })
expect(await teamCommand(['off', SIGN_OUT_BUTTON_FLAG], quiet.deps)).toBe(0)
expect(quiet.out.join('\n')).toContain('harness login')
expect(quiet.deps.startDaemon).toHaveBeenCalled()
const json = fake()
json.setSession({ ...computer, kind: 'team' })
expect(await teamCommand(['off', '--json', SIGN_OUT_BUTTON_FLAG], json.deps)).toBe(0)
expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: true, changed: true, next: 'harness login' })
const notTeam = fake()
expect(await teamCommand(['off'], notTeam.deps)).toBe(0)
expect(notTeam.out[0]).toContain('nothing to change')
})
})
describe('internal verbs', () => {
it('__handoff prints the code and nothing else', async () => {
const f = fake()
expect(await teamCommand(['__handoff'], f.deps)).toBe(0)
expect(f.out).toEqual([CODE])
const team = fake()
team.setSession({ ...computer, kind: 'team' })
expect(await teamCommand(['__handoff'], team.deps)).toBe(1)
expect(team.out).toEqual([])
})
const inTeam = (over: Partial<TeamCommandDeps> = {}) => {
const f = fake({ user: () => 'harnessteam', readConfig: () => config, ...over })
f.setSession(null)
return f
}
it('__start redeems the handed-over code for this computer, stores a team session and reports it with the check', async () => {
const f = inTeam()
expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)
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)
expect(f.out.join('\n')).toContain('[team] signed in for team work')
expect(f.out.join('\n')).toContain('[team] engines: claude installed, codex signed in')
const broken = inTeam({ engines: vi.fn(async () => { throw new Error('no home') }) })
expect(await teamCommand(['__start'], broken.deps)).toBe(0)
expect(broken.out.join('\n')).toContain('could not check the engines: no home')
})
it('__start replaces a historical sign-in success when no Team session remains', async () => {
const f = inTeam()
f.status.set(STATUS, { version: 1, signIn: { state: 'signed-in', at: 1 } })
await teamCommand(['__start'], f.deps)
expect(f.status.get(STATUS)?.signIn).toMatchObject({ state: 'signed-out', at: 1_000_000 })
})
it('__start pins the handed sign-in to its redeemed account', async () => {
const f = inTeam()
await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)
expect(f.session()?.signInAcct).toBe('user-placeholder-1')
expect(f.deps.get).toHaveBeenCalledWith('/api/auth/me', {
authorization: 'Bearer hna_team', 'x-autonomous-env': 'prod',
})
})
it('__start does not pin a replacement sign-in when the account lookup returns late', async () => {
const f = inTeam()
f.deps.get = vi.fn(async () => {
f.setSession({ ...computer, signInEpoch: 'replacement@1000001' })
return { user: { id: 'previous-owner' } }
}) as never
await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)
expect(f.session()?.signInEpoch).toBe('replacement@1000001')
expect(f.session()?.signInAcct).toBeUndefined()
})
it('__start keeps a redeemed sign-in and reports an account lookup failure', async () => {
const f = inTeam({ get: vi.fn(async () => { throw new Error('offline') }) as never })
await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)
expect(f.session()).toMatchObject({ kind: 'team', refreshToken: 'hnr_team' })
expect(f.out.join('\n')).toContain('could not record the signed-in account')
expect(f.status.get(STATUS)?.signIn?.state).toBe('signed-in')
})
// Task #3262 (Amon, 11-05): Repair handed his Harness Team account to him, but the sign-in it made was adopted, so its device
// key log stayed kelvin's and froze, and it refused his daemon. A sign-in from the handoff file is the owner's own setup run,
// behind the macOS password: made by hand, at this run, so the log may start over for the account it was handed to.
it('__start gives a handed-over sign-in an epoch made by hand at this run, never an adopted one', async () => {
const f = inTeam()
expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)
expect(signInOf(f.session()!.signInEpoch)).toMatchObject({ adopted: false, at: f.deps.now() })
// `harness team on` at this computer's own terminal hands nothing over: its sign-in stays adopted, as it always was.
const on = fake({ interactive: true })
expect(await teamCommand(['on'], on.deps)).toBe(0)
expect(signInOf(on.session()!.signInEpoch)).toMatchObject({ adopted: true })
})
it('__start stores nothing when the backend makes a session that is not a team one', async () => {
const f = inTeam()
f.post.mockImplementation(async (path: string) => path === '/api/auth/handoff/redeem' ? { token: 'hna_phone', refreshToken: 'hnr_phone' } : {})
expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)
expect(f.session()).toBeNull()
expect(f.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed', detail: expect.stringContaining('does not make team sign-ins yet') })
})
it('__start reports a refused code and an unsafe file, and still exits 0 so the daemon starts', async () => {
const refused = inTeam({ post: (async () => { throw Object.assign(new Error('expired'), { status: 401 }) }) as never })
expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], refused.deps)).toBe(0)
expect(refused.session()).toBeNull()
expect(refused.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed' })
const unsafe = inTeam({ takeHandoff: () => { throw new Error('not this account\'s private file') } })
expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], unsafe.deps)).toBe(0)
expect(unsafe.status.get(STATUS)?.signIn).toMatchObject({ state: 'failed', detail: 'not this account\'s private file' })
})
// Echo, reviewing #2637: the Team side of a lookup that outlives its sign-in.
describe('a Team machine lookup that outlives its sign-in', () => {
const start = async (startedUnder: string | undefined, meanwhile: Partial<AuthSession>) => {
const f = inTeam({ takeHandoff: () => null })
f.setSession({ ...computer, kind: 'team', refreshToken: 'htr_first', machineId: undefined, signInEpoch: startedUnder })
const answer = f.post.getMockImplementation()!
f.post.mockImplementation(async (path: string, body: unknown, headers?: Record<string, string>) => {
if (path === '/api/machines/resolve-computer') f.setSession({ ...f.session()!, ...meanwhile })
return answer(path, body, headers)
})
expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)
return f
}
const SWITCHED = { refreshToken: 'htr_other_owner', signInEpoch: 'adopted:team:next@2' }
it('an owner switch while it is out: the old answer writes nothing and claims nothing', async () => {
const f = await start('adopted:team:first@1', SWITCHED)
expect(f.session()).toMatchObject(SWITCHED)
expect(f.session()?.machineId).toBeUndefined()
expect(f.out.join('\n')).not.toContain('runs as machine')
})
it('a switch away from a Team sign-in from before epochs: dropped too', async () => {
const f = await start(undefined, SWITCHED)
expect(f.session()?.machineId).toBeUndefined()
expect(f.out.join('\n')).not.toContain('runs as machine')
})
it('the same sign-in, refreshed while it is out: the answer is kept', async () => {
const f = await start('adopted:team:first@1', { accessToken: 'hna_refreshed' })
expect(f.session()).toMatchObject({ machineId: 'm-team', accessToken: 'hna_refreshed', signInEpoch: 'adopted:team:first@1' })
expect(f.out.join('\n')).toContain('runs as machine m-team')
})
it('a sign-in from before epochs, only given one meanwhile: the answer is kept', async () => {
const f = await start(undefined, { signInEpoch: 'adopted:abc@1' })
expect(f.session()).toMatchObject({ machineId: 'm-team', signInEpoch: 'adopted:abc@1' })
})
})
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', refreshToken: 'htr_old' })
await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], signed.deps)
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)')
const owner = fake({ readConfig: () => config })
await teamCommand(['__start'], owner.deps)
expect(owner.deps.writeStatus).not.toHaveBeenCalled()
expect(owner.deps.privacy).not.toHaveBeenCalled()
})
})
describe('on Linux', () => {
const LINUX_HOME = '/home/owner-placeholder'
const LINUX_STATUS = '/var/lib/harness/team/status.json'
const linuxConfig: TeamConfig = {
...config, home: '/home/harnessteam', ownerHome: LINUX_HOME, sentinel: `${LINUX_HOME}/.harness-team-privacy`, label: 'harness-team.service',
plist: '/etc/systemd/system/harness-team.service', statusFile: LINUX_STATUS,
node: '/home/harnessteam/.harness/runtime/node-v1/bin/node', cli: '/home/harnessteam/.harness/cli/cli.js',
}
const onLinux = (over: Parameters<typeof fake>[0] = {}) => fake({
platform: 'linux', home: () => LINUX_HOME, hostname: () => 'linux-placeholder',
installed: () => ({ cliDir: `${LINUX_HOME}/.harness/cli`, cliJs: `${LINUX_HOME}/.harness/cli/cli.js`,
node: `${LINUX_HOME}/.harness/runtime/node-v1/bin/node`, nodeRuntimeDir: `${LINUX_HOME}/.harness/runtime/node-v1`, tmuxRuntimeDir: null }),
...over,
})
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 } })
expect(await teamCommand(['status'], f.deps)).toBe(0)
expect(f.deps.jobState).toHaveBeenCalledWith('harness-team.service')
const text = f.out.join('\n')
for (const needle of ['● running (pid 4242)', '✓ signed in (30s ago)', 'Private ✓', `${LINUX_HOME} · mode 700 ✓`, '/home/harnessteam',
'a standard user with a locked password, never an administrator', '/etc/harness/team.json and /var/lib/harness/team/',
'sudo systemctl disable --now harness-team.service', 'sudo userdel -r harnessteam', 'sudo rm /etc/systemd/system/harness-team.service',
'/var/lib/harness/team-relay-owner-placeholder', `rm ${LINUX_HOME}/.harness-team-privacy`]) {
expect(text, needle).toContain(needle)
}
expect(text).not.toMatch(/dscl|launchctl|LaunchDaemon|Users & Groups/)
// No subscription relay since #4137: nothing says the account may use the owner's subscriptions.
expect(text).not.toMatch(/subscription|relay /)
})
it('remove runs the Linux removal with sudo in a terminal and takes the team computer off the owner\'s account', async () => {
const f = onLinux({ readConfig: () => linuxConfig, interactive: true,
adminResult: { ok: true, stdout: `harness: deleted the account harnessteam\nharness: team computer ${TEAM_COMPUTER}\n` } })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.vias[0]).toBe('sudo')
expect(f.built[0]!.script).toContain('userdel -r "$TEAM"')
expect(f.built[0]!.script).toContain("RELAY_DIR='/var/lib/harness/team-relay-owner-placeholder'")
expect(f.deps.delete).toHaveBeenCalledWith('/api/machines/m-team', { authorization: 'Bearer x' })
const text = f.out.join('\n')
expect(text).toContain('✓ Removed the Harness Team account (harnessteam), /home/harnessteam and the daemon harness-team.service.')
expect(text).not.toMatch(/Mac|macOS/)
})
it('remove, when Linux keeps the account, says nothing was removed', async () => {
const f = onLinux({ readConfig: () => linuxConfig, interactive: true,
adminResult: { ok: false, code: 'FAILED', status: 9, message: 'could not delete the account harnessteam: userdel: user harnessteam is currently used by process 4242. Nothing was removed: the Harness Team account and its daemon run as before' } })
expect(await teamCommand(['remove'], f.deps)).toBe(1)
const text = f.err.join('\n')
expect(text).toContain('Linux kept the Harness Team account')
expect(text).not.toMatch(/macOS|Users & Groups|tccutil/)
})
it('team on refuses on a Linux computer that has the account, which runs its team work', async () => {
const f = onLinux({ readConfig: () => linuxConfig })
expect(await teamCommand(['on', '--yes'], f.deps)).toBe(1)
expect(f.err[0]).toContain('This computer has a Harness Team account')
expect(f.post).not.toHaveBeenCalled()
})
it('reads systemd\'s answer for the team daemon', () => {
expect(parseSystemctlShow(0, 'LoadState=loaded\nActiveState=active\nMainPID=812\n')).toEqual({ loaded: true, pid: 812, state: 'active' })
expect(parseSystemctlShow(0, 'MainPID=0\nActiveState=failed\nLoadState=loaded\n')).toEqual({ loaded: true, pid: null, state: 'failed' })
expect(parseSystemctlShow(0, 'LoadState=not-found\nActiveState=inactive\nMainPID=0\n')).toEqual({ loaded: false, pid: null, state: null })
expect(parseSystemctlShow(1, '')).toEqual({ loaded: false, pid: null, state: null })
})
})
describe('on Windows', () => {
const WIN_HOME = 'C:\\Users\\DELL'
const WIN_SID = 'S-1-5-21-3073114020-2660841771-734626734-1001'
const WIN_STATUS = 'C:\\ProgramData\\Harness\\Team\\status.json'
const NODE = 'node-v22.23.2-win32-x64'
const winConfig: TeamConfig = {
...config, home: 'C:\\Users\\harnessteam', owner: 'DELL', ownerSid: WIN_SID, ownerHome: WIN_HOME, sentinel: `${WIN_HOME}\\.harness-team-privacy`,
label: '\\Harness\\Harness Team', plist: 'C:\\Windows\\System32\\Tasks\\Harness\\Harness Team', statusFile: WIN_STATUS,
node: `C:\\Users\\harnessteam\\.harness\\runtime\\${NODE}\\node.exe`, cli: 'C:\\Users\\harnessteam\\.harness\\cli\\cli.js',
}
const onWindows = (over: Parameters<typeof fake>[0] & { handedOver?: string[] } = {}) => {
const handed = over.handedOver ?? []
return fake({
platform: 'win32', user: () => 'DELL', home: () => WIN_HOME, uid: () => -1, hostname: () => 'DESKTOP-0TFH0OJ',
stage: `${WIN_HOME}\\AppData\\Local\\Temp\\harness-team-stage`,
installed: () => ({ cliDir: `${WIN_HOME}\\.harness\\cli\\0.4.97`, cliJs: `${WIN_HOME}\\.harness\\cli\\0.4.97\\cli.js`,
node: `${WIN_HOME}\\.harness\\runtime\\${NODE}\\node.exe`, nodeRuntimeDir: `${WIN_HOME}\\.harness\\runtime\\${NODE}`, tmuxRuntimeDir: null,
ptyDir: `${WIN_HOME}\\.harness\\runtime\\pty\\0.2.4` }),
ownerSid: vi.fn(async () => WIN_SID),
handOver: vi.fn((code: string) => { handed.push(code) }),
startTeamTask: vi.fn(async () => true),
adminResult: { ok: true, stdout: 'harness: the team daemon\'s task \\Harness\\Harness Team runs as harnessteam from startup\n' },
...over,
})
}
// Task #2686: on Windows the sign-in and the daemon's start come after the elevated script, from the owner.
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' })) })
f.status.set(WIN_STATUS, { version: 1, signIn: { state: 'signed-in', at: 1_000_000 - 30_000 }, privacy: { passed: true, checkedAt: 1_000_000 - 60_000 } })
expect(await teamCommand(['status'], f.deps)).toBe(0)
const text = f.out.join('\n')
for (const needle of ['● running (pid 4242)', '✓ signed in (30s ago)', 'Private ✓', `your home ${WIN_HOME} · private ✓`, 'C:\\Users\\harnessteam',
'a standard user (Users only) with a random password nobody knows', 'C:\\ProgramData\\Harness\\team.json and C:\\ProgramData\\Harness\\Team\\',
'Unregister-ScheduledTask -TaskPath \'\\Harness\\\' -TaskName \'Harness Team\'', 'Remove-LocalUser harnessteam', 'C:\\ProgramData\\Harness\\team-relay-DELL',
`${WIN_HOME}\\.harness-team-privacy`]) {
expect(text, needle).toContain(needle)
}
expect(text).not.toMatch(/subscription|relay /)
expect(text).not.toMatch(/dscl|launchctl|LaunchDaemon|systemctl|mode 700/)
})
it('remove runs the Windows removal through User Account Control and takes the team computer off the owner\'s account', async () => {
const f = onWindows({ readConfig: () => winConfig, interactive: true,
adminResult: { ok: true, stdout: `harness: deleted the account harnessteam\nharness: Windows still holds the registry of harnessteam; the rest of C:\\Users\\harnessteam (3 items) is removed at the next restart\nharness: team computer ${TEAM_COMPUTER}\n` } })
expect(await teamCommand(['remove'], f.deps)).toBe(0)
expect(f.vias[0]).toBe('prompt')
expect(f.built[0]!.script).toContain('Remove-LocalUser -Name $TEAM')
expect(f.deps.delete).toHaveBeenCalledWith('/api/machines/m-team', { authorization: 'Bearer x' })
const text = f.out.join('\n')
expect(text).toContain('✓ Removed the Harness Team account (harnessteam), C:\\Users\\harnessteam and the daemon \\Harness\\Harness Team.')
expect(text).toContain('is removed at the next restart')
expect(text).not.toMatch(/Mac|macOS|mode 700|sudo/)
})
it('remove, when something of the account still holds its profile, says nothing was removed', async () => {
const f = onWindows({ readConfig: () => winConfig,
adminResult: { ok: false, code: 'FAILED', status: 9, message: 'could not remove the profile C:\\Users\\harnessteam (in use). Nothing was removed: the Harness Team account and its daemon run as before' } })
expect(await teamCommand(['remove'], f.deps)).toBe(1)
const text = f.err.join('\n')
expect(text).toContain('Windows kept the Harness Team account')
expect(text).not.toMatch(/macOS|Users & Groups|tccutil|Linux/)
})
it('team on refuses on a Windows computer that has the account', async () => {
const f = onWindows({ readConfig: () => winConfig })
expect(await teamCommand(['on', '--yes'], f.deps)).toBe(1)
expect(f.err[0]).toContain('This computer has a Harness Team account')
})
it('team __start reads the code from the handover folder, a Windows path', async () => {
const f = onWindows({ user: () => 'harnessteam', readConfig: () => winConfig })
expect(await teamCommand(['__start', 'C:\\ProgramData\\Harness\\Team\\handoff\\team-handoff'], f.deps)).toBe(0)
expect(f.deps.takeHandoff).toHaveBeenCalledWith('C:\\ProgramData\\Harness\\Team\\handoff\\team-handoff')
expect(f.status.get(WIN_STATUS)).toMatchObject({ signIn: { state: 'signed-in' }, privacy: { passed: true } })
})
})
describe('parseLaunchctlPrint', () => {
it('reads the pid and state, and a job launchd does not know as not loaded', () => {
expect(parseLaunchctlPrint(0, 'system/ai.autonomous.harness.team = {\n\tstate = running\n\tpid = 812\n}')).toEqual({ loaded: true, pid: 812, state: 'running' })
expect(parseLaunchctlPrint(0, '\tstate = not running\n')).toEqual({ loaded: true, pid: null, state: 'not running' })
expect(parseLaunchctlPrint(113, 'Could not find service')).toEqual({ loaded: false, pid: null, state: null })
})
})
describe('harness team logs and sign-in', () => {
const config = { version: 1, user: 'harnessteam', realName: 'Harness Team', home: '/Users/harnessteam', owner: 'owner',
ownerHome: '/Users/owner', sentinel: '/Users/owner/.harness-team-privacy', port: 18493, label: 'ai.autonomous.harness.team',
plist: '/Library/LaunchDaemons/ai.autonomous.harness.team.plist', statusFile: '/Library/Application Support/Harness/Team/status.json',
node: '/Users/harnessteam/.harness/runtime/node/bin/node', cli: '/Users/harnessteam/.harness/cli/cli.js', env: {},
createdAt: '2026-10-27T10:37:42.635Z' }
it('reads the team log through the one administrator prompt, and says when there is no account', async () => {
const f = fake({ readConfig: () => config as never, adminResult: { ok: true, stdout: '2026-11-03 14:23:01 [agent] create pane open\n' } })
expect(await teamCommand(['logs'], f.deps)).toBe(0)
expect(f.built[0]!.script).toContain("tail -n 40 '/Users/harnessteam/.harness/cli/data/harness.log'")
expect(f.out.join('\n')).toContain('create pane open')
const none = fake()
expect(await teamCommand(['logs'], none.deps)).toBe(1)
expect(none.err.join('\n')).toContain('No Harness Team account')
})
it('reads the team log on Windows too, quoting its path for PowerShell', async () => {
const f = fake({ platform: 'win32', adminResult: { ok: true, stdout: '2026-11-03 14:23:01 [agent] create pane open\n' },
readConfig: () => ({ ...config, home: "C:\\Users\\O'Team" }) as never })
expect(await teamCommand(['logs', '--lines=5'], f.deps)).toBe(0)
expect(f.built[0]!.script).toContain("Get-Content -LiteralPath 'C:\\Users\\O''Team")
expect(f.built[0]!.script).toContain('-Tail 5 -Encoding UTF8 -ErrorAction Stop')
expect(f.out.join('\n')).toContain('create pane open')
})
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()
}
})
})