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
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
import { randomUUID } from 'node:crypto'
const mocks = vi.hoisted(() => ({
prisma: { harnessShare: { findFirst: vi.fn(), findMany: vi.fn(), findUnique: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },
machine: { findFirst: vi.fn(), findMany: vi.fn() }, user: { findMany: vi.fn(), findUnique: vi.fn() }, harnessLink: { findMany: vi.fn() } },
mayOpenShare: vi.fn(), presence: vi.fn(), changed: vi.fn(), listChanged: vi.fn(), auth: vi.fn(),
}))
// The list asks about every share at once; share by share it answers as mayOpenShare would (integration/harnessSharesList.test.ts).
vi.mock('../superTabs/store.js', () => ({ SuperTabStore: class {
mayOpenShare = mocks.mayOpenShare
openableShares = async (user: unknown, shares: unknown[]) => {
const open = []
for (const share of shares) if (await mocks.mayOpenShare(user, share)) open.push(share)
return open
}
} }))
vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: mocks.presence, publishShareChanged: mocks.changed,
publishDeviceMachineListChanged: mocks.listChanged }))
vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))
import { harnessShareRoutes, recipientShare, SHARES_TOLD_MS } from './harnessShares.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
import { errorHandler } from '../middlewares/errorHandler.js'
import { logger } from '../utils/logger.js'
const owner = { sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }
const ken = { sub: 'ken', email: ' [email protected] ', role: 'user', autonomousEnv: 'prod' as const }
const machine = { machineId: 'm1', userId: owner.sub, name: 'Design studio', authMode: 'remote', billingStatus: 'not_required' }
const input = () => ({ machineId: 'm1', agentId: 'agent-1', name: 'My harness', engine: 'codex',
recipientEmail: '[email protected]', ownerPublicKey: Buffer.alloc(32, 1).toString('base64'),
expiresAt: new Date(Date.now() + 30 * 86400_000).toISOString() })
describe('account-bound harness invitations', () => {
let app: FastifyInstance
beforeEach(async () => {
vi.resetAllMocks()
mocks.mayOpenShare.mockResolvedValue(true)
mocks.auth.mockResolvedValue(owner)
mocks.prisma.machine.findFirst.mockResolvedValue(machine)
mocks.prisma.machine.findMany.mockResolvedValue([machine])
mocks.prisma.user.findMany.mockResolvedValue([{ id: owner.sub, name: 'D', email: owner.email }])
mocks.prisma.harnessShare.findMany.mockResolvedValue([])
mocks.prisma.harnessLink.findMany.mockResolvedValue([])
mocks.prisma.harnessShare.updateMany.mockResolvedValue({ count: 1 })
mocks.presence.mockResolvedValue(new Map([['m1', true]]))
app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, mocks.auth)
await app.register(harnessShareRoutes); await app.ready()
})
afterEach(async () => { await app.close(); vi.restoreAllMocks() })
const auth = { authorization: 'Bearer fixture' }
function put(payload: unknown = input(), id: string = randomUUID()) {
return app.inject({ method: 'PUT', url: `/api/harness-shares/${id}`, headers: auth, payload: payload as any })
}
it('requires SSO on every endpoint', async () => {
for (const method of ['GET', 'PUT', 'DELETE'] as const) {
expect((await app.inject({ method, url: `/api/harness-shares${method === 'GET' ? '' : `/${randomUUID()}`}` })).statusCode).toBe(401)
}
expect(mocks.prisma.harnessShare.findMany).not.toHaveBeenCalled()
})
it('publishes an owner invitation with normalized email and the authenticated account/environment', async () => {
const id = randomUUID(), data = { ...input(), recipientEmail: ' [email protected] ' }
expect((await put(data, id)).json()).toEqual({ success: true, data: { id } })
expect(mocks.prisma.machine.findFirst).toHaveBeenCalledWith({ where: expect.objectContaining({
machineId: 'm1', userId: owner.sub, autonomousEnv: 'prod', OR: expect.any(Array),
}) })
expect(mocks.prisma.harnessShare.upsert).toHaveBeenCalledWith({ where: { id },
create: expect.objectContaining({ id, recipientEmail: '[email protected]', ownerId: 'owner', autonomousEnv: 'prod', revokedAt: null }),
update: expect.objectContaining({ recipientEmail: '[email protected]', expiresAt: expect.any(Date) }) })
expect(mocks.changed).toHaveBeenCalledWith(id)
})
it('rejects invalid emails, expired/overlong invitations, unknown fields, unsafe machine IDs and keys', async () => {
for (const patch of [{ recipientEmail: 'bad' }, { expiresAt: new Date(0).toISOString() },
{ expiresAt: new Date(Date.now() + 92 * 86400_000).toISOString() }, { ownerPublicKey: 'bad' },
{ machineId: '../machine' }, { canControl: true }, { name: '' }, { agentId: '' }]) {
expect((await put({ ...input(), ...patch })).statusCode).toBe(400)
}
expect((await put(input(), 'not-a-uuid')).statusCode).toBe(400)
expect(mocks.prisma.harnessShare.upsert).not.toHaveBeenCalled()
})
it('forbids sharing another owner’s machine, suspended machines, and self invitations', async () => {
mocks.prisma.machine.findFirst.mockResolvedValueOnce(null)
expect((await put()).statusCode).toBe(403)
mocks.prisma.machine.findFirst.mockResolvedValueOnce({ ...machine, billingStatus: 'suspended' })
expect((await put()).statusCode).toBe(403)
const self = await put({ ...input(), recipientEmail: ' [email protected] ' })
expect(self.statusCode).toBe(400); expect(self.json().error.code).toBe('SELF_INVITE')
expect(mocks.prisma.harnessShare.upsert).not.toHaveBeenCalled()
})
it('cannot repurpose an existing grant for another account, machine, agent or email', async () => {
for (const patch of [{ ownerId: 'other' }, { machineId: 'other' }, { agentId: 'other' }, { recipientEmail: '[email protected]' }]) {
mocks.prisma.harnessShare.findUnique.mockResolvedValueOnce({ ...input(), ownerId: owner.sub, ...patch })
expect((await put()).statusCode).toBe(403)
}
mocks.prisma.harnessShare.findUnique.mockResolvedValueOnce({ ...input(), ownerId: owner.sub })
expect((await put()).statusCode).toBe(200)
})
// Diego's issue file (2026-10-27): a daemon that lost its grants file sends a new id for a recipient it already invited;
// the unique machine, agent and recipient index refused it as a 500, which the CLI retried forever.
it('PUT with a new id for an existing recipient is 409, not 500', async () => {
const { Prisma } = await import('@prisma/client')
const taken = () => new Prisma.PrismaClientKnownRequestError('Unique constraint failed', { code: 'P2002', clientVersion: 'test' })
mocks.prisma.harnessShare.upsert.mockRejectedValue(taken())
mocks.prisma.harnessShare.findFirst.mockResolvedValue({ id: 'existing-id', ownerId: owner.sub })
const res = await put()
expect(res.statusCode).toBe(409)
expect(res.json().error).toMatchObject({ code: 'SHARE_EXISTS', id: 'existing-id' })
expect(mocks.prisma.harnessShare.findFirst).toHaveBeenCalledWith({ where: { machineId: 'm1', agentId: 'agent-1', recipientEmail: '[email protected]' },
select: { id: true, ownerId: true } })
expect(mocks.changed).not.toHaveBeenCalled()
// A row from the machine's earlier owner is theirs: still a conflict, without its id.
mocks.prisma.harnessShare.findFirst.mockResolvedValue({ id: 'earlier-id', ownerId: 'earlier-owner' })
const earlier = await put()
expect(earlier.statusCode).toBe(409)
expect(earlier.json().error).not.toHaveProperty('id')
// Any other failure to save is not a conflict: it stays a 500, and nobody is told of an invitation not saved.
mocks.prisma.harnessShare.upsert.mockRejectedValue(new Prisma.PrismaClientKnownRequestError('Transaction conflict', { code: 'P2034', clientVersion: 'test' }))
expect((await put()).statusCode).toBe(500)
mocks.prisma.harnessShare.upsert.mockRejectedValue(new Error('db down'))
expect((await put()).statusCode).toBe(500)
expect(mocks.changed).not.toHaveBeenCalled()
})
it('discovers only active invitations for the signed-in email and environment, without machine secrets', async () => {
mocks.auth.mockResolvedValue(ken)
mocks.prisma.harnessShare.findMany.mockResolvedValue([
{ id: 'ken-grant', ...input(), ownerId: owner.sub, expiresAt: new Date(input().expiresAt) },
{ id: 'old-owner-grant', ...input(), ownerId: 'previous-owner', expiresAt: new Date(input().expiresAt) },
])
mocks.prisma.machine.findMany.mockResolvedValue([machine,
{ ...machine, machineId: 'no-grants' }, { ...machine, machineId: 'suspended', billingStatus: 'suspended' }])
const response = await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })
expect(response.json().data.machines).toEqual([{
machineId: 'm1', name: 'Design studio', authMode: 'remote', status: 'running', shared: true, ownerName: 'D',
shares: [{ id: 'ken-grant', agentId: 'agent-1', name: 'My harness', engine: 'codex',
ownerPublicKey: input().ownerPublicKey, expiresAt: expect.any(String) }],
}])
expect(mocks.prisma.harnessShare.findMany).toHaveBeenCalledWith({ where: {
recipientEmail: '[email protected]', autonomousEnv: 'prod', revokedAt: null, expiresAt: { gt: expect.any(Date) },
}, orderBy: { createdAt: 'asc' }, take: 1000 })
})
it('retains offline invitations and handles unnamed owners and missing metadata', async () => {
mocks.prisma.harnessShare.findMany.mockResolvedValue([{ id: 's', ...input(), engine: null, ownerId: 'owner', expiresAt: new Date(input().expiresAt) }])
mocks.presence.mockResolvedValue(new Map())
mocks.prisma.user.findMany.mockResolvedValue([{ id: 'owner', name: null, email: owner.email }])
const response = () => app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })
expect((await response()).json().data.machines[0]).toMatchObject({ status: 'offline', ownerName: owner.email })
mocks.prisma.user.findMany.mockResolvedValue([])
expect((await response()).json().data.machines[0].ownerName).toBe('Harness user')
})
it('removes only the owner’s invitation and publishes revocation after persistence', async () => {
const id = randomUUID()
const remove = () => app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })
expect((await remove()).json()).toEqual({ success: true, data: { removed: true } })
expect(mocks.prisma.harnessShare.updateMany).toHaveBeenCalledWith({ where: { id, ownerId: 'owner', autonomousEnv: 'prod', OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date) } })
expect(mocks.changed).toHaveBeenCalledWith(id)
mocks.prisma.harnessShare.updateMany.mockResolvedValue({ count: 0 })
expect((await remove()).statusCode).toBe(404)
expect(mocks.changed).toHaveBeenCalledTimes(1)
})
// diego@'s 0.4.55 dev build took back the same invitations every few seconds and renewed others as often; each
// poked every member's every app to re-read its machines and shares (2026-10-26, the backend at its CPU limit).
it('answers a repeated revocation and a renewal without telling anyone again', async () => {
const id = randomUUID()
mocks.prisma.harnessShare.updateMany.mockResolvedValue({ count: 0 })
mocks.prisma.harnessShare.findFirst.mockResolvedValue({ id })
const removed = await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })
expect(removed.json()).toEqual({ success: true, data: { removed: true } })
const saved = { id, ...input(), ownerId: 'owner', superTabId: null, revokedAt: null, expiresAt: new Date(input().expiresAt) }
mocks.prisma.harnessShare.findUnique.mockResolvedValue(saved)
expect((await put({ ...input(), expiresAt: new Date(Date.now() + 31 * 86400_000).toISOString() }, id)).statusCode).toBe(200)
expect(mocks.prisma.harnessShare.upsert).toHaveBeenCalledTimes(1)
expect(mocks.changed).not.toHaveBeenCalled()
expect(mocks.listChanged).not.toHaveBeenCalled()
// What the recipient sees, changed: told.
for (const change of [{ name: 'Renamed' }, { engine: 'claude' }, { superTabId: 'c51479bd73b59e58176ad9e4' }]) {
mocks.prisma.harnessShare.findUnique.mockResolvedValue(saved)
await put({ ...input(), ...change }, id)
}
mocks.prisma.harnessShare.findUnique.mockResolvedValue({ ...saved, revokedAt: new Date() })
await put(input(), id)
expect(mocks.changed).toHaveBeenCalledTimes(4)
})
it('tells the invited account that its list changed, so its apps need not poll for invitations', async () => {
const info = vi.spyOn(logger, 'info').mockImplementation(() => logger)
const id = randomUUID()
// First read is the "may this grant be changed" check (no row yet); the second is the saved invitation.
mocks.prisma.harnessShare.findUnique.mockResolvedValueOnce(null).mockResolvedValue({ id, recipientEmail: '[email protected]' })
mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })
expect((await put(input(), id)).statusCode).toBe(200)
expect(mocks.prisma.user.findUnique).toHaveBeenCalledWith({ where: { email: '[email protected]' }, select: { id: true } })
expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'harness_shares' })
// Named in the log, so a burst of `machines_changed` on someone's app can be traced to the invitation behind it.
expect(info).toHaveBeenCalledWith('harness share: told the recipient it changed', { shareId: id, recipientId: 'ken' })
})
// Task #3925 (Ken's scan, 11-06): a Swarm's agent restarts made a share per new agent for each member, and each one told every
// app of theirs to read its shares again: a burst of starts was a burst of share-list reads. A recipient is told at once, then
// at most once more a window, so the last change is never lost.
it('tells a recipient once for a burst of changes, then once more when the burst is over', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
try {
mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })
for (let i = 0; i < 5; i++) {
const id = randomUUID()
mocks.prisma.harnessShare.findUnique.mockResolvedValueOnce(null).mockResolvedValueOnce({ id, recipientEmail: '[email protected]' })
expect((await put({ ...input(), agentId: `agent-${i}` }, id)).statusCode).toBe(200)
}
expect(mocks.listChanged).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(SHARES_TOLD_MS)
expect(mocks.listChanged).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(SHARES_TOLD_MS * 2)
expect(mocks.listChanged).toHaveBeenCalledTimes(2)
} finally { vi.useRealTimers() }
})
it('tells the invited account when the owner takes the invitation back', async () => {
const id = randomUUID()
mocks.prisma.harnessShare.findUnique.mockResolvedValue({ id, recipientEmail: '[email protected]' })
mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })
expect((await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })).statusCode).toBe(200)
expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'harness_shares' })
})
it('makes the viewers of the agent’s private links check again when the invitation behind them changes', async () => {
const id = randomUUID()
mocks.prisma.harnessShare.findUnique.mockResolvedValue({ id, ...input(), ownerId: 'owner', autonomousEnv: 'prod', superTabId: null,
revokedAt: new Date(), expiresAt: new Date(input().expiresAt) })
mocks.prisma.harnessLink.findMany.mockResolvedValue([{ id: 'link-1' }, { id: 'link-2' }])
expect((await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })).statusCode).toBe(200)
expect(mocks.prisma.harnessLink.findMany).toHaveBeenCalledWith({ where: { ownerId: 'owner', machineId: 'm1', agentId: 'agent-1',
autonomousEnv: 'prod', revokedAt: null, visibility: { not: 'public' } }, select: { id: true } })
expect(mocks.changed.mock.calls).toEqual([[id], ['link-1'], ['link-2']])
})
it('invites an address with no account yet, and survives the lookup failing, without telling anyone', async () => {
const id = randomUUID(), remove = () => app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })
mocks.prisma.harnessShare.findUnique.mockResolvedValue({ id, recipientEmail: '[email protected]' })
mocks.prisma.user.findUnique.mockResolvedValue(null)
expect((await remove()).statusCode).toBe(200)
mocks.prisma.user.findUnique.mockRejectedValue(new Error('db unavailable'))
expect((await remove()).statusCode).toBe(200)
mocks.prisma.harnessShare.findUnique.mockResolvedValue(null)
expect((await remove()).statusCode).toBe(200)
expect(mocks.listChanged).not.toHaveBeenCalled()
})
it('rechecks exact recipient, expiry, current machine ownership and billing on socket admission', async () => {
const grant = { ...input(), id: 'share', ownerId: 'owner' }
mocks.prisma.harnessShare.findFirst.mockResolvedValue(null)
expect(await recipientShare('share', ken)).toBeNull()
mocks.prisma.harnessShare.findFirst.mockResolvedValue(grant)
expect(await recipientShare('share', ken)).toEqual(grant)
expect(mocks.prisma.harnessShare.findFirst).toHaveBeenLastCalledWith({ where: { id: 'share', recipientEmail: '[email protected]', autonomousEnv: 'prod', revokedAt: null, expiresAt: { gt: expect.any(Date) } } })
expect(mocks.prisma.machine.findFirst).toHaveBeenLastCalledWith({ where: expect.objectContaining({ machineId: 'm1', userId: 'owner', autonomousEnv: 'prod', OR: expect.any(Array) }) })
mocks.prisma.machine.findFirst.mockResolvedValueOnce(null)
expect(await recipientShare('share', ken)).toBeNull()
mocks.prisma.machine.findFirst.mockResolvedValueOnce({ ...machine, billingStatus: 'pending' })
expect(await recipientShare('share', ken)).toBeNull()
})
// A team machine (lib/teamSession.ts) hosts Swarm agents for teammates. Its daemon shares an agent's terminal with the
// Swarm members who may watch it, and nothing else: only its own machine's harnesses, only for a Swarm.
it('lets a team session share only its own machine\'s harnesses, for a Swarm, and take back only those', async () => {
const TEAM_COMPUTER = 'b'.repeat(32)
const teamMachine = { ...machine, machineId: 'team-mac', computerId: TEAM_COMPUTER, sessionKind: 'team' }
mocks.auth.mockResolvedValue({ ...owner, harnessSessionId: 'team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER })
mocks.prisma.machine.findMany.mockResolvedValue([teamMachine])
mocks.prisma.machine.findFirst.mockResolvedValue(teamMachine)
const swarm = { ...input(), machineId: 'team-mac', superTabId: 'a'.repeat(24) }
expect((await put(swarm)).statusCode).toBe(200)
for (const payload of [{ ...swarm, machineId: 'm1' }, { ...swarm, superTabId: null }, { ...input(), machineId: 'team-mac' }]) {
const res = await put(payload)
expect(res.statusCode).toBe(403)
expect(res.json().error.code).toBe('TEAM_SESSION_LIMITED')
}
expect(mocks.prisma.harnessShare.upsert).toHaveBeenCalledTimes(1)
const id = randomUUID()
expect((await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })).statusCode).toBe(200)
expect(mocks.prisma.harnessShare.updateMany).toHaveBeenLastCalledWith({ where: { id, ownerId: 'owner', autonomousEnv: 'prod', machineId: 'team-mac', OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] },
data: { revokedAt: expect.any(Date) } })
})
it('rechecks Super Tab membership for session admission and excludes revoked views from inventory', async () => {
mocks.auth.mockResolvedValue(ken)
const share = { id: 'share', ...input(), superTabId: 'a'.repeat(24), ownerId: owner.sub, expiresAt: new Date(input().expiresAt) }
mocks.prisma.harnessShare.findFirst.mockResolvedValue(share)
mocks.prisma.harnessShare.findMany.mockResolvedValue([share])
expect(await recipientShare('share', ken)).toEqual(share)
expect(mocks.mayOpenShare).toHaveBeenCalledWith(ken, share)
mocks.mayOpenShare.mockResolvedValue(false)
expect(await recipientShare('share', ken)).toBeNull()
expect((await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })).json().data.machines).toEqual([])
})
// Prisma sends an empty list as `$or: []`, a scan of all machines (prod slow log, 2026-11-04): most people have no share.
it('reads no machines or owners for a person with no share', async () => {
const response = await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })
expect(response.json().data.machines).toEqual([])
expect(mocks.prisma.machine.findMany).not.toHaveBeenCalled()
expect(mocks.prisma.user.findMany).not.toHaveBeenCalled()
})
it('reads no owners when none of the shared machines is usable', async () => {
mocks.prisma.harnessShare.findMany.mockResolvedValue([{ id: 's', ...input(), engine: null, ownerId: 'owner', expiresAt: new Date(input().expiresAt) }])
mocks.prisma.machine.findMany.mockResolvedValue([])
expect((await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })).json().data.machines).toEqual([])
expect(mocks.prisma.user.findMany).not.toHaveBeenCalled()
})
it('asks the Swarms about an ordinary share too: a confidential session refuses it (final review, Critical 1)', async () => {
mocks.auth.mockResolvedValue(ken)
const share = { id: 'share', ...input(), superTabId: null, ownerId: owner.sub, expiresAt: new Date(input().expiresAt) }
mocks.prisma.harnessShare.findFirst.mockResolvedValue(share)
mocks.prisma.harnessShare.findMany.mockResolvedValue([share])
mocks.mayOpenShare.mockResolvedValue(false)
expect(await recipientShare('share', ken)).toBeNull()
expect(mocks.mayOpenShare).toHaveBeenCalledWith(ken, share)
expect((await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })).json().data.machines).toEqual([])
})
})