Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Verify account sharing through three daemons and real live viewers

Deeb59a8a8811c7
diff --git a/.gitignore b/.gitignore
index f6feeca39..42ffbcf91 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,7 @@ node_modules/
.vite/
dist/
.tsbuildinfo
+coverage/
.DS_Store
# IDE state. workspace.xml records local paths, run configs and sometimes datasource
# credentials — none of it belongs in a public repo.
diff --git a/backend/src/lib/observerWs.test.ts b/backend/src/lib/observerWs.test.ts
new file mode 100644
index 000000000..9c7d91c34
--- /dev/null
+++ b/backend/src/lib/observerWs.test.ts
@@ -0,0 +1,132 @@
+import { EventEmitter } from 'node:events'
+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
+const m = vi.hoisted(() => ({
+ auth: vi.fn(), grant: vi.fn(), up: vi.fn(), changed: vi.fn(), down: vi.fn(), live: vi.fn(),
+ upgrade: vi.fn(),
+}))
+vi.mock('./ssoAuth.js', () => ({ authenticateAccessToken: m.auth }))
+vi.mock('../routes/harnessShares.js', () => ({ recipientShare: m.grant }))
+vi.mock('./bus.js', () => ({ publishDown: m.down, subscribeUp: m.up, subscribeShareChanged: m.changed }))
+vi.mock('./hub.js', () => ({ trackSocketLiveness: m.live }))
+vi.mock('./wsServer.js', () => ({ WS_LIMITS: { web: 1 }, createWss: () => ({ handleUpgrade: m.upgrade }) }))
+import { attachObserver, handleObserverUpgrade } from './observerWs.js'
+const user = { sub: 'ken', email: ' [email protected] ', autonomousEnv: 'prod' as const, role: 'user' }
+const share = { id: '11111111-1111-4111-8111-111111111111', machineId: 'm', agentId: 'a' }
+class Socket extends EventEmitter {
+ readyState = 1; bufferedAmount = 0
+ send = vi.fn()
+ close = vi.fn((_code?: number, _reason?: string) => { this.readyState = 3; this.emit('close') })
+ terminate = vi.fn(() => this.close())
+ message(type: string, payload: unknown = {}) { this.emit('message', Buffer.from(JSON.stringify({ type, payload })), false) }
+}
+const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve() }
+describe('isolated observer WebSocket boundary', () => {
+ let ws: Socket, upward: (message: any) => void, changed: () => void, disposeUp: ReturnType<typeof vi.fn<() => void>>, disposeShare: ReturnType<typeof vi.fn<() => void>>, disposeLive: ReturnType<typeof vi.fn<() => void>>
+ beforeEach(() => {
+ vi.useFakeTimers(); vi.resetAllMocks(); ws = new Socket()
+ disposeUp = vi.fn(); disposeShare = vi.fn(); disposeLive = vi.fn()
+ m.auth.mockResolvedValue(user); m.grant.mockResolvedValue(share)
+ m.down.mockResolvedValue(1); m.live.mockReturnValue(disposeLive)
+ m.up.mockImplementation(async (_id, callback) => { upward = callback; return disposeUp })
+ m.changed.mockImplementation(async (_id, callback) => { changed = callback; return disposeShare })
+ m.upgrade.mockImplementation((_req, _socket, _head, done) => done(ws))
+ })
+ afterEach(() => { ws.close(); vi.useRealTimers() })
+ const attach = () => attachObserver(ws as never, user, share as never)
+ const hello = () => ws.message('observer_hello', { ephemeral: Buffer.alloc(32, 1).toString('base64') })
+ it('routes only invitation-scoped traffic and only targeted observer output', async () => {
+ await attach()
+ expect(JSON.parse(ws.send.mock.calls[0][0] as string)).toEqual({ type: 'observer_connected' })
+ hello(); await flush()
+ expect(m.down).toHaveBeenCalledWith('m', { connId: expect.stringMatching(/^observer:/), frame: {
+ type: 'observer_open', payload: { shareId: share.id, email: '[email protected]', ephemeral: Buffer.alloc(32, 1).toString('base64') },
+ } })
+ const connId = m.down.mock.calls[0][1].connId
+ for (const type of ['agents', 'message', 'e2e_welcome', 'terminal_ready']) upward({ targetConnId: connId, frame: { type } })
+ upward({ targetConnId: 'someone-else', frame: { type: 'observer_frame' } })
+ expect(ws.send).toHaveBeenCalledTimes(1)
+ for (const type of ['observer_welcome', 'observer_frame', 'observer_closed']) upward({ targetConnId: connId, frame: { type } })
+ expect(ws.send).toHaveBeenCalledTimes(4)
+ ws.message('observer_frame', { __e2e: { encrypted: true } }); await flush()
+ expect(m.down.mock.calls[1][1]).toEqual({ connId, frame: { type: 'observer_frame', payload: { __e2e: { encrypted: true } } } })
+ ws.close(); ws.emit('close')
+ expect(disposeLive).toHaveBeenCalledTimes(1); expect(disposeUp).toHaveBeenCalledTimes(1); expect(disposeShare).toHaveBeenCalledTimes(1)
+ upward({ targetConnId: connId, frame: { type: 'observer_frame' } })
+ expect(ws.send).toHaveBeenCalledTimes(4)
+ expect(m.down.mock.calls.at(-1)?.[1].frame.type).toBe('observer_close')
+ })
+ it('revocation notifications and periodic checks close active viewers', async () => {
+ await attach(); m.grant.mockResolvedValue(null); changed(); await flush()
+ expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))
+ ws = new Socket(); m.grant.mockResolvedValue(share); await attach()
+ m.grant.mockResolvedValue(null); await vi.advanceTimersByTimeAsync(5000)
+ expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))
+ })
+ it('database and owner outages are recoverable; admission rechecks race-safe authority', async () => {
+ m.grant.mockResolvedValue(null); await attach()
+ expect(ws.send).not.toHaveBeenCalled()
+ ws = new Socket(); m.grant.mockResolvedValue(share); await attach()
+ upward({ frame: { type: 'node_status', payload: { online: false } } })
+ expect(ws.close).toHaveBeenCalledWith(1012, 'Owner is offline')
+ ws = new Socket(); m.grant.mockRejectedValue(new Error('db down')); await attach()
+ expect(ws.close).toHaveBeenCalledWith(1013, 'Sharing temporarily unavailable')
+ })
+ it('bounds and validates messages, rejecting control APIs and repeated handshakes', async () => {
+ for (const send of [
+ () => ws.message('agent_delete'), () => ws.message('observer_frame', { __e2e: {} }),
+ () => ws.message('observer_hello', { ephemeral: 'bad' }),
+ () => ws.emit('message', Buffer.from('garbage'), false),
+ () => ws.emit('message', Buffer.from('{}'), true),
+ () => ws.emit('message', Buffer.alloc(65 * 1024), false),
+ () => ws.emit('message', [Buffer.alloc(65 * 1024)], false),
+ ]) {
+ ws = new Socket(); await attach(); send(); await flush()
+ expect(ws.close).toHaveBeenCalledWith(1008, expect.any(String))
+ }
+ ws = new Socket(); await attach(); hello(); await flush(); hello(); await flush()
+ expect(ws.close).toHaveBeenCalledWith(1008, expect.any(String))
+ })
+ it('bounds rate, resets the window and preserves message order across async publication', async () => {
+ await attach(); hello(); await flush()
+ await vi.advanceTimersByTimeAsync(1000)
+ for (let i = 0; i < 121; i++) { ws.message('observer_frame', { __e2e: {} }); await flush() }
+ expect(ws.close).toHaveBeenCalledWith(1008, 'Invalid observer message')
+ ws = new Socket(); await attach();
+ let release!: () => void
+ m.down.mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(1) }))
+ hello(); await flush(); ws.message('observer_frame', { __e2e: {} }); await flush()
+ const before = m.down.mock.calls.length; release(); await flush()
+ expect(m.down.mock.calls.length).toBe(before + 1)
+ })
+ it('handles publication errors and subscriptions completing after a disconnect', async () => {
+ await attach(); m.down.mockRejectedValueOnce(new Error('relay down')); hello(); await flush()
+ expect(ws.close).toHaveBeenCalledWith(1013, 'Owner unavailable')
+ ws = new Socket(); await attach(); hello(); await flush()
+ m.down.mockRejectedValueOnce(new Error('relay down')); ws.message('observer_frame', { __e2e: {} }); await flush()
+ expect(ws.close).toHaveBeenCalledWith(1013, 'Owner unavailable')
+ ws = new Socket()
+ let release!: (value: () => void) => void
+ m.changed.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+ const attaching = attach(); ws.close(); release(() => disposeShare()); await attaching
+ expect(disposeShare).toHaveBeenCalled(); expect(ws.send).not.toHaveBeenCalled()
+ })
+ it('authenticates upgrades before admission and rejects absent/invalid grants', async () => {
+ const socket = { destroyed: false, destroy: vi.fn() }
+ const req = (url: string, token = 'fixture') => ({ url, headers: { 'sec-websocket-protocol': token } })
+ for (const request of [req('/api/observer-ws?share=bad'), req(`/api/observer-ws?share=${share.id}`, '')]) {
+ handleObserverUpgrade(request as never, socket as never, Buffer.alloc(0)); await flush()
+ }
+ expect(socket.destroy).toHaveBeenCalledTimes(2); expect(m.auth).not.toHaveBeenCalled()
+ handleObserverUpgrade(req(`/api/observer-ws?share=${share.id}&autonomousEnv=prod`) as never, socket as never, Buffer.alloc(0)); await flush()
+ expect(m.auth).toHaveBeenCalledWith('fixture', 'prod'); expect(m.upgrade).toHaveBeenCalledTimes(1)
+ ws.close(); ws = new Socket(); m.grant.mockResolvedValueOnce(null)
+ handleObserverUpgrade(req(`/api/observer-ws?share=${share.id}`) as never, socket as never, Buffer.alloc(0)); await flush()
+ expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))
+ m.auth.mockRejectedValueOnce(new Error('invalid'))
+ handleObserverUpgrade(req(`/api/observer-ws?share=${share.id}`) as never, socket as never, Buffer.alloc(0)); await flush()
+ expect(socket.destroy).toHaveBeenCalledTimes(3)
+ socket.destroyed = true
+ handleObserverUpgrade(req(`/api/observer-ws?share=${share.id}`) as never, socket as never, Buffer.alloc(0)); await flush()
+ expect(m.upgrade).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.ts
new file mode 100644
index 000000000..4239d18f8
--- /dev/null
+++ b/backend/src/routes/harnessShares.test.ts
@@ -0,0 +1,134 @@
+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() } },
+ presence: vi.fn(), changed: vi.fn(), auth: vi.fn(),
+}))
+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 }))
+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))
+import { harnessShareRoutes, recipientShare } from './harnessShares.js'
+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
+import { errorHandler } from '../middlewares/errorHandler.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.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.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() })
+ 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)
+ })
+ 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' }, 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)
+ })
+ 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()
+ })
+})
diff --git a/cli/scripts/share-harness-e2e.ts b/cli/scripts/share-harness-e2e.ts
new file mode 100644
index 000000000..f6fd193fe
--- /dev/null
+++ b/cli/scripts/share-harness-e2e.ts
@@ -0,0 +1,245 @@
+/** Real backend, Mongo/Redis, three isolated daemons, tmux and Chrome. Only SSO and the model are fixtures.
+ * HARNESS_SHARE_E2E_SERVICES points to {"mongo":"mongodb://127.0.0.1:.../?replicaSet=...","redis":"redis://127.0.0.1:..."}.
+ * Services MUST be disposable. Every daemon, browser, identity, terminal and project belongs to this run.
+ */
+import assert from 'node:assert/strict'
+import { spawn, execFile, type ChildProcess } from 'node:child_process'
+import { createServer } from 'node:http'
+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'
+import { createWriteStream } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { promisify } from 'node:util'
+import { randomUUID } from 'node:crypto'
+import { inflateSync } from 'node:zlib'
+import { WebSocket } from 'ws'
+import { decodeTerminalLocal, encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from '../src/lib/terminalBinary.js'
+
+if (!process.env.HARNESS_SHARE_E2E_SERVICES) throw new Error('Set HARNESS_SHARE_E2E_SERVICES to disposable service URLs.')
+const exec = promisify(execFile), repo = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
+const root = await mkdtemp(join(tmpdir(), 'harness-share-e2e-'))
+const services = JSON.parse(await readFile(process.env.HARNESS_SHARE_E2E_SERVICES, 'utf8'))
+const mongo = new URL(services.mongo), redis = new URL(services.redis)
+assert.equal(mongo.hostname, '127.0.0.1'); assert.equal(redis.hostname, '127.0.0.1')
+mongo.pathname = `/sharing_${randomUUID().replaceAll('-', '')}`
+const children: ChildProcess[] = [], sockets: WebSocket[] = []
+const tmuxSockets: string[] = []
+const accounts = ['owner', 'ken', 'diego', 'stranger'].map(name => ({ name, token: randomUUID(), id: randomUUID(), email: `${name}@sharing.local.invalid` }))
+let backendUrl = ''
+const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
+async function until(label: string, check: () => boolean | Promise<boolean>, timeout = 30_000) {
+ const end = Date.now() + timeout
+ while (Date.now() < end) { if (await check()) return; await delay(60) }
+ throw new Error(`Timed out: ${label}. Logs: ${root}`)
+}
+async function freePort() {
+ const server = createServer()
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const port = (server.address() as { port: number }).port
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ return port
+}
+function run(name: string, cwd: string, args: string[], env: NodeJS.ProcessEnv) {
+ const child = spawn(process.execPath, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] })
+ const log = createWriteStream(join(root, `${name}.log`)); child.stdout!.pipe(log); child.stderr!.pipe(log)
+ children.push(child); return child
+}
+async function stop(child: ChildProcess) {
+ if (!child.pid || child.exitCode != null || child.signalCode != null) return
+ try { process.kill(-child.pid, 'SIGTERM') } catch { return }
+ await until('child exit', () => child.exitCode != null || child.signalCode != null, 5000)
+ .catch(() => { try { process.kill(-child.pid!, 'SIGKILL') } catch {} })
+}
+async function api(account: typeof accounts[number], path: string, method = 'GET', body?: unknown) {
+ const response = await fetch(backendUrl + path, { method,
+ headers: { authorization: `Bearer ${account.token}`, 'content-type': 'application/json', 'x-autonomous-env': 'prod' },
+ body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(20_000) })
+ return { status: response.status, body: await response.json() as any }
+}
+class Peer {
+ readonly frames: any[] = []
+ readonly binary: TerminalBinaryClear[] = []
+ text = ''; stream = ''; closedCode: number | undefined; private inputSequence = 0
+ private heartbeat: NodeJS.Timeout
+ constructor(readonly ws: WebSocket) {
+ sockets.push(ws)
+ ws.on('message', (raw, binary) => {
+ if (binary) {
+ const frame = decodeTerminalLocal(new Uint8Array(raw as Buffer))
+ if (!frame) return
+ this.binary.push(frame)
+ this.text += (frame.compressed ? inflateSync(frame.bytes) : Buffer.from(frame.bytes)).toString()
+ this.send('terminal_ack', { streamId: frame.streamId, seq: frame.seq })
+ } else {
+ const frame = JSON.parse(raw.toString()); this.frames.push(frame)
+ if (frame.type === 'terminal_ready') { this.stream = frame.payload.streamId; this.inputSequence = 0 }
+ }
+ })
+ ws.on('error', () => {})
+ ws.on('close', code => { this.closedCode = code; clearInterval(this.heartbeat) })
+ this.heartbeat = setInterval(() => { if (this.stream) this.send('terminal_alive', { streamId: this.stream }) }, 5000)
+ }
+ static async connect(port: number, machineId: string, shareId?: string) {
+ const peer = new Peer(new WebSocket(`ws://127.0.0.1:${port}/api/local-ws`))
+ await new Promise<void>((resolve, reject) => { peer.ws.once('open', resolve); peer.ws.once('error', reject) })
+ peer.send('machine_select', { machineId, localProtocolVersion: 1, ...(shareId ? { shareId } : {}) })
+ await until('local peer admission', () => peer.frames.some(f => f.type === 'connected') || peer.closedCode !== undefined)
+ return peer
+ }
+ send(type: string, payload: Record<string, unknown> = {}) {
+ if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type, payload }))
+ }
+ async rpc(type: string, payload: Record<string, unknown> = {}) {
+ const requestId = randomUUID(); this.send(type, { ...payload, requestId })
+ await until(type, () => this.frames.some(f => f.payload?.requestId === requestId))
+ return this.frames.find(f => f.payload?.requestId === requestId)!.payload
+ }
+ async open(agentId: string, cols = 120, rows = 40) {
+ const response = await this.rpc('terminal_open', { protocolVersion: 3, agentId, cols, rows })
+ assert.ok(!response.code && this.stream, JSON.stringify(response))
+ await until('terminal snapshot', () => this.binary.some(f => f.kind === TerminalBinaryKind.keyframe))
+ return response
+ }
+ input(text: string) {
+ const frame = encodeTerminalLocal({ kind: TerminalBinaryKind.input, streamId: this.stream, seq: this.inputSequence++, compressed: false, bytes: Buffer.from(text) })!
+ this.ws.send(frame)
+ }
+ async close() { clearInterval(this.heartbeat); this.ws.close(); await until('socket close', () => this.closedCode !== undefined) }
+}
+const sso = createServer((req, res) => {
+ const user = accounts.find(a => req.headers.authorization === `Bearer ${a.token}`)
+ res.setHeader('content-type', 'application/json')
+ if (!user) { res.writeHead(401); res.end('{}'); return }
+ res.end(JSON.stringify({ status: 1, data: { id: user.id, email: user.email } }))
+})
+let success = false
+try {
+ await new Promise<void>(resolve => sso.listen(0, '127.0.0.1', resolve))
+ const [backendPort, proxyPort] = await Promise.all([freePort(), freePort()])
+ backendUrl = `http://127.0.0.1:${backendPort}`
+ const backendEnv = { ...process.env, NODE_ENV: 'test', PORT: String(backendPort), PORT_APP_PROXY: String(proxyPort),
+ DATABASE_URL: mongo.href, REDIS_URL: redis.href, HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false',
+ SSO_PROFILE_URL: `http://127.0.0.1:${(sso.address() as { port: number }).port}/profile`,
+ TERMINAL_P2P_ROLLOUT_PERCENT: '0', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }
+ await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], { cwd: join(repo, 'backend'), env: backendEnv, timeout: 60_000 })
+ run('backend', join(repo, 'backend'), ['--import', 'tsx', 'src/server.ts'], backendEnv)
+ await until('backend', async () => fetch(`${backendUrl}/api/health`).then(r => r.ok).catch(() => false))
+ const engine = join(root, 'codex')
+ await writeFile(engine, `#!${process.execPath}\nif (process.argv.includes('--version')) { console.log('codex-cli 1.0.0'); process.exit(0) }\nprocess.title = 'codex'; process.stdin.setRawMode?.(true); console.log('SHARING_READY'); process.stdin.on('data', x => process.stdout.write('ECHO:' + x + '\\r\\n')); setInterval(() => {}, 1000);\n`, { mode: 0o700 })
+ const fixture = join(root, 'harness-source')
+ await mkdir(join(fixture, 'template'), { recursive: true })
+ await writeFile(join(fixture, 'harness.json'), JSON.stringify({ spec: 1, id: 'fixture/sharing', name: 'Sharing demo', engine: 'codex',
+ workspace: { template: 'template', marker: 'result.txt' }, agent: { instructions: 'AGENTS.md' },
+ viewer: { command: './viewer.mjs', url: 'http://127.0.0.1:${port}/' }, verdict: '.harness/verdict.json' }))
+ await writeFile(join(fixture, 'AGENTS.md'), 'Share harness test fixture.\n')
+ await writeFile(join(fixture, 'template/result.txt'), 'Sharing demo')
+ await writeFile(join(fixture, 'viewer.mjs'), `#!${process.execPath}\nimport { createServer } from 'node:http';\ncreateServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<html><body style="background:#152238;color:white;font:40px sans-serif"><h1>Live harness</h1><p id="clock"></p><script>setInterval(() => document.getElementById("clock").textContent=Date.now(), 200)</script></body></html>'); }).listen(Number(process.env.HARNESS_VIEWER_PORT), '127.0.0.1');\n`, { mode: 0o700 })
+ const machines: Array<{ machineId: string; port: number; env: NodeJS.ProcessEnv; child: ChildProcess; socket: string; workspace: string }> = []
+ for (const account of accounts.slice(0, 3)) {
+ const folder = join(root, account.name), data = join(folder, 'data'), auth = join(folder, 'auth'), workspace = join(folder, 'project')
+ for (const dir of [data, auth, workspace]) await mkdir(dir, { recursive: true })
+ const computerId = randomUUID(), port = await freePort(), socket = join(folder, 'tmux.sock')
+ tmuxSockets.push(socket)
+ const registered = await api(account, '/api/machines/resolve-computer', 'POST', { computerId, label: `${account.name} test machine` })
+ assert.equal(registered.status, 200, JSON.stringify(registered))
+ const machineId = registered.body.data.machine.machineId
+ await writeFile(join(auth, 'session.json'), JSON.stringify({ version: 1, accessToken: account.token, refreshToken: 'fixture-refresh',
+ expiresAt: Date.now() + 3_600_000, autonomousEnv: 'prod', computerId, machineId, updatedAt: Date.now() }), { mode: 0o600 })
+ await exec('tmux', ['-S', socket, '-f', '/dev/null', 'new-session', '-d', '-s', 'fixture-keeper'])
+ const env = { ...process.env, NODE_ENV: 'test', TMUX: `${socket},0,0`, PORT: String(port), HARNESS_AUTH_DIR: auth,
+ ADAPTER_COMPUTER_ID: computerId, ADAPTER_COMPUTER_ID_FILE: join(folder, 'computer-id'), ADAPTER_DATA_DIR: data,
+ ADAPTER_RUNTIME_DIR: join(folder, 'runtime'), DSH_DIR: join(folder, 'dsh'), CODEX_PATH: engine,
+ BACKEND_WS_URL: `ws://127.0.0.1:${backendPort}`, WEB_URL: backendUrl, HARNESS_STORE_CATALOG_URL: 'http://127.0.0.1:9/catalog',
+ DISABLE_HOOK_INSTALL: 'true', ADAPTER_UPDATE_DISABLE: 'true', ANALYTICS_ENABLED: 'false', RECAP_FORCE: 'false',
+ RECAP_WITHOUT_DEVICE: 'false', CABLE_DISABLE: 'true', CABLE_FW_DISABLE: 'true', TERMINAL_BACKENDS: 'tmux',
+ CLAUDE_PROJECTS_DIR: join(folder, 'claude-projects') }
+ if (account.name === 'owner') await exec(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'dsh', 'install', fixture, '--link'], { cwd: join(repo, 'cli'), env, timeout: 30_000 })
+ const child = run(account.name, join(repo, 'cli'), ['--import', 'tsx', 'src/cli.ts', '__run'], env)
+ await until(`${account.name} daemon`, async () => fetch(`http://127.0.0.1:${port}/api/status`, { headers: { 'x-adapter-local': '1' } }).then(r => r.json()).then((r: any) => r.connected === true).catch(() => false))
+ machines.push({ machineId, port, env, child, socket, workspace })
+ }
+ const [host, kenMachine, diegoMachine] = machines
+ let owner = await Peer.connect(host.port, host.machineId)
+ const created = await owner.rpc('agent_create', { creationId: randomUUID(), engine: 'codex', cwd: host.workspace, dsh: 'fixture/sharing' })
+ assert.equal(created.state, 'created', JSON.stringify(created)); const agentId = created.agent.id
+ console.log('Created owner harness', agentId)
+ await owner.open(agentId, 110, 33)
+ await until('fixture model ready', () => owner.text.includes('SHARING_READY'))
+ owner.input('owner-before-sharing')
+ await until('owner terminal input', () => owner.text.includes('ECHO:owner-before-sharing'))
+ console.log('Owner input verified; inviting Ken and Diego')
+ const invitation = await owner.rpc('harness_share_invite', { agentId, emails: [accounts[1].email.toUpperCase(), accounts[2].email], days: 30 })
+ assert.equal(invitation.shares.length, 2, JSON.stringify(invitation))
+ assert.ok(invitation.shares.every((s: any) => !s.pending && !s.error), JSON.stringify(invitation))
+ const kenShare = invitation.shares.find((s: any) => s.email === accounts[1].email).id
+ const diegoShare = invitation.shares.find((s: any) => s.email === accounts[2].email).id
+ for (const account of accounts.slice(1, 3)) {
+ const discovery = await api(account, '/api/harness-shares')
+ assert.equal(discovery.body.data.machines.length, 1)
+ const m = discovery.body.data.machines[0]
+ assert.equal(m.shared, true); assert.equal(m.status, 'running'); assert.equal(m.shares.length, 1)
+ assert.equal(m.shares[0].agentId, agentId); assert.ok(!m.apiKey && !m.computerId && !m.hostname)
+ }
+ assert.deepEqual((await api(accounts[3], '/api/harness-shares')).body.data.machines, [])
+ assert.equal((await api(accounts[1], `/api/harness-shares/${kenShare}`, 'DELETE')).status, 404)
+ console.log('Account discovery verified; connecting observers')
+ let ken = await Peer.connect(kenMachine.port, host.machineId, kenShare)
+ const diego = await Peer.connect(diegoMachine.port, host.machineId, diegoShare)
+ for (const peer of [ken, diego]) {
+ const ready = await peer.open(agentId, 200, 100)
+ assert.equal(ready.readOnly, true)
+ const frame = peer.binary.find(f => f.kind === TerminalBinaryKind.keyframe)!
+ assert.equal(frame.cols, 110); assert.equal(frame.rows, 33)
+ assert.ok(peer.text.includes('owner-before-sharing'))
+ assert.equal((await peer.rpc('agent_delete', { agentId })).error, 'VIEW_ONLY')
+ assert.equal((await peer.rpc('terminal_resize', { streamId: peer.stream, cols: 1, rows: 1 })).error, 'VIEW_ONLY')
+ peer.input('UNAUTHORIZED_INPUT')
+ peer.send('observer_viewer', { agentId })
+ }
+ owner.input('two-observers-世界')
+ await until('owner and both observers receive live output', () => [owner, ken, diego].every(p => p.text.includes('ECHO:two-observers-世界')))
+ assert.ok(!owner.text.includes('UNAUTHORIZED_INPUT'))
+ await until('two recipients receive live viewer pixels', () => [ken, diego].every(p => p.frames.some(f => f.type === 'observer_viewer' && f.payload.state === 'live')), 45_000)
+ const firstImage = ken.frames.find(f => f.type === 'observer_viewer' && f.payload.state === 'live').payload.data
+ assert.equal(Buffer.from(firstImage, 'base64').subarray(0, 2).toString('hex'), 'ffd8')
+ await until('viewer visibly updates', () => ken.frames.some(f => f.type === 'observer_viewer' && f.payload.data && f.payload.data !== firstImage))
+ assert.equal((await owner.rpc('harness_share_list', { agentId })).shares.reduce((n: number, s: any) => n + s.watching, 0), 2)
+ await ken.close()
+ ken = await Peer.connect(kenMachine.port, host.machineId, kenShare); await ken.open(agentId)
+ owner.input('reconnected-observer')
+ await until('observer reconnect catches up', () => ken.text.includes('ECHO:reconnected-observer'))
+ await owner.rpc('harness_share_remove', { agentId, id: kenShare })
+ await until('immediate removal closes Ken', () => ken.closedCode === 4403)
+ assert.deepEqual((await api(accounts[1], '/api/harness-shares')).body.data.machines, [])
+ owner.input('only-diego-now')
+ await until('Diego continues while Ken loses access', () => diego.text.includes('ECHO:only-diego-now'))
+ assert.ok(!ken.text.includes('only-diego-now'))
+ const denied = await Peer.connect(kenMachine.port, host.machineId, kenShare)
+ assert.equal(denied.closedCode, 4403)
+ await owner.close(); await stop(host.child)
+ await until('owner disconnect is recoverable', () => diego.closedCode === 1012)
+ await until('offline grant stays discoverable', async () => (await api(accounts[2], '/api/harness-shares')).body.data.machines[0]?.status === 'offline')
+ host.child = run('owner-restarted', join(repo, 'cli'), ['--import', 'tsx', 'src/cli.ts', '__run'], host.env)
+ await until('owner restarted', async () => fetch(`http://127.0.0.1:${host.port}/api/status`, { headers: { 'x-adapter-local': '1' } }).then(r => r.json()).then((r: any) => r.connected === true).catch(() => false))
+ owner = await Peer.connect(host.port, host.machineId)
+ assert.equal((await owner.rpc('harness_share_list', { agentId })).shares.length, 1)
+ const rejoined = await Peer.connect(diegoMachine.port, host.machineId, diegoShare); await rejoined.open(agentId)
+ await owner.open(agentId); owner.input('after-daemon-restart')
+ await until('durable permission reconnect', () => rejoined.text.includes('ECHO:after-daemon-restart'))
+ await owner.rpc('harness_share_remove', { agentId, id: diegoShare })
+ await until('last observer removed', () => rejoined.closedCode === 4403)
+ success = true
+ console.log('PASS: invite → account discovery → two read-only observers → encrypted live terminal/viewer → denied controls → reconnect → immediate revocation → offline discovery → durable daemon restart.')
+} catch (error) {
+ console.error(error)
+ throw error
+} finally {
+ for (const ws of sockets) ws.terminate()
+ await Promise.all(children.reverse().map(stop))
+ for (const socket of tmuxSockets) await exec('tmux', ['-S', socket, 'kill-server'], { timeout: 3000 }).catch(() => {})
+ sso.closeAllConnections()
+ await new Promise<void>(resolve => sso.close(() => resolve()))
+ if (success && process.env.HARNESS_SHARE_KEEP !== '1') await rm(root, { recursive: true, force: true })
+ else console.error(`Sharing E2E logs: ${root}`)
+}
diff --git a/cli/src/sharing/owner.spec.ts b/cli/src/sharing/owner.spec.ts
index eb5cda81b..929f6fd29 100644
--- a/cli/src/sharing/owner.spec.ts
+++ b/cli/src/sharing/owner.spec.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -8,7 +8,7 @@ import type { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinat
import type { TerminalStreamSink } from '../lib/terminalTypes.js'
import { decodeTerminalLocal, TerminalBinaryKind } from '../lib/terminalBinary.js'
import { HarnessGrantStore } from './grants.js'
-import { HarnessShareOwner } from './owner.js'
+import { HarnessShareOwner, type ShareOwnerDeps } from './owner.js'
import { recipientHandshake, type ObserverCipher } from './crypto.js'
describe('owner authority and read-only observation', () => {
@@ -16,7 +16,7 @@ describe('owner authority and read-only observation', () => {
const identity = newIdentity()
let frames: Array<{ id: string; type: string; payload: any }>
let agents: Map<string, RegisteredSession>
- let publish: ReturnType<typeof vi.fn>, send: ReturnType<typeof vi.fn>, watchViewer: ReturnType<typeof vi.fn>
+ let publish: Mock<ShareOwnerDeps['publish']>, send: Mock<ShareOwnerDeps['send']>, watchViewer: Mock<NonNullable<ShareOwnerDeps['watchViewer']>>
let opened: Array<{ sink: TerminalStreamSink; handle: any }>
let machineId: string
beforeEach(() => {
@@ -26,13 +26,13 @@ describe('owner authority and read-only observation', () => {
frames = []; opened = []; machineId = 'machine'
agents = new Map([['agent', { agentId: 'agent', sessionId: 's', engine: 'codex',
active: true, projectPath: '/tmp/project', runtimes: [{ backend: 'tmux', paneId: '%1' }],
- primaryRuntimeKey: 'tmux:default:%1' } as RegisteredSession]])
+ primaryRuntimeKey: 'tmux:default:%1' } as unknown as RegisteredSession]])
publish = vi.fn(async () => ({ status: 200, body: {} }))
send = vi.fn((id, type, payload) => { frames.push({ id, type, payload }); return true })
watchViewer = vi.fn((_id, callback) => { callback({ state: 'live', data: 'jpeg' }); return vi.fn() })
owner = new HarnessShareOwner({ machineId: () => machineId, identity, grants: store,
resolveAgent: id => agents.get(id), send, publish, watchViewer,
- terminals: { openStream: async (_agent, _size, sink, readOnly) => {
+ terminals: { openStream: async (_agent: RegisteredSession, _size: unknown, sink: TerminalStreamSink, readOnly: boolean) => {
expect(readOnly).toBe(true)
const handle = { runtime: { backend: 'tmux', paneId: '%1' },
snapshot: vi.fn(async () => ({ state: 'succeeded', value: { bytes: Buffer.from('hello'), cols: 120, rows: 40 } })),
diff --git a/cli/src/sharing/relay.spec.ts b/cli/src/sharing/relay.spec.ts
new file mode 100644
index 000000000..d68485f6b
--- /dev/null
+++ b/cli/src/sharing/relay.spec.ts
@@ -0,0 +1,132 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { AuthSessionManager } from '../lib/authSession.js'
+import { b64e, newIdentity } from '../lib/e2ee/core.js'
+import { ownerHandshake } from './crypto.js'
+const state = vi.hoisted(() => ({ sockets: [] as any[], stop: vi.fn() }))
+vi.mock('ws', async () => {
+ const { EventEmitter } = await import('node:events')
+ class FakeWebSocket extends EventEmitter {
+ static OPEN = 1
+ readyState = 1
+ send = vi.fn()
+ terminate = vi.fn(() => { this.readyState = 3; this.emit('close', 1006, Buffer.alloc(0)) })
+ constructor(...args: unknown[]) { super(); state.sockets.push(this); (this as any).args = args }
+ }
+ return { WebSocket: FakeWebSocket }
+})
+vi.mock('../lib/wsLiveness.js', () => ({ watchSocketLiveness: () => ({ stop: state.stop }) }))
+import { HarnessShareRelay, SharingEndedError } from './relay.js'
+import { SHARE_REQUEST_TYPES, SHARE_RESULT_TYPES } from './protocol.js'
+describe('recipient relay', () => {
+ const identity = newIdentity()
+ const share = { id: 'share', agentId: 'agent', name: 'Demo', engine: null,
+ ownerPublicKey: b64e(identity.pub), expiresAt: new Date(Date.now() + 100000).toISOString() }
+ let relay: HarnessShareRelay
+ let discover: ReturnType<typeof vi.fn<() => Promise<any[]>>>
+ let sink: { sendFrame: ReturnType<typeof vi.fn>; sendBinary: ReturnType<typeof vi.fn> }, closed: ReturnType<typeof vi.fn<(code: number, reason: string) => void>>
+ beforeEach(() => {
+ vi.useFakeTimers(); state.sockets = []; state.stop.mockReset()
+ sink = { sendFrame: vi.fn(() => true), sendBinary: vi.fn(() => true) }; closed = vi.fn()
+ discover = vi.fn(async () => [{ machineId: 'machine', shares: [share] }])
+ relay = new HarnessShareRelay({ accessToken: async () => 'signed-in-token' } as AuthSessionManager,
+ 'ws://localhost:1234/', 'prod', discover)
+ })
+ afterEach(() => { relay.close(); vi.useRealTimers() })
+ async function begin() {
+ const pending = relay.acquire('machine', 'share', sink as never, closed)
+ await Promise.resolve(); await Promise.resolve()
+ const ws = state.sockets.at(-1)
+ ws.emit('open')
+ return { pending, ws }
+ }
+ function frame(ws: any, type: string, payload: unknown = {}) { ws.emit('message', Buffer.from(JSON.stringify({ type, payload }))) }
+ async function ready() {
+ const { pending, ws } = await begin()
+ frame(ws, 'observer_connected')
+ const hello = JSON.parse(ws.send.mock.calls[0][0])
+ const owner = ownerHandshake(identity, 'machine', 'share', hello.payload.ephemeral)
+ frame(ws, 'observer_welcome', owner.welcome)
+ return { session: await pending, ws, owner }
+ }
+ it('uses the account token and exact grant, authenticates the owner, and decrypts terminal/viewer output', async () => {
+ const { session, ws, owner } = await ready()
+ expect(ws.args).toEqual(['ws://localhost:1234/api/observer-ws?share=share&autonomousEnv=prod', ['signed-in-token'], expect.any(Object)])
+ expect(sink.sendFrame).toHaveBeenCalledWith({ type: 'connected', payload: { machineId: 'machine', e2ee: false, readOnly: true } })
+ await session.send({ type: 'terminal_open', payload: { agentId: 'agent' } })
+ const packet = JSON.parse(ws.send.mock.calls.at(-1)[0])
+ expect(packet.type).toBe('observer_frame')
+ expect(owner.cipher.open(packet.payload)).toEqual({ type: 'terminal_open', payload: { agentId: 'agent' } })
+ frame(ws, 'observer_frame', owner.cipher.seal({ type: 'observer_binary', payload: { bytes: Buffer.from('output').toString('base64') } }))
+ expect(sink.sendBinary).toHaveBeenCalledWith(Buffer.from('output'))
+ frame(ws, 'observer_frame', owner.cipher.seal({ type: 'observer_viewer', payload: { state: 'live', data: 'pixels' } }))
+ expect(sink.sendFrame).toHaveBeenCalledWith({ type: 'observer_viewer', payload: { state: 'live', data: 'pixels' } })
+ frame(ws, 'observer_frame', owner.cipher.seal({ type: 'observer_binary', payload: { bytes: 5 } }))
+ expect(sink.sendBinary).toHaveBeenCalledTimes(1)
+ await session.sendBinary({} as never)
+ session.detach()
+ expect(state.stop).toHaveBeenCalled(); expect(closed).not.toHaveBeenCalled()
+ const count = ws.send.mock.calls.length
+ await session.send({ type: 'terminal_alive' })
+ expect(ws.send).toHaveBeenCalledTimes(count)
+ })
+ it('refuses unpublished or wrong-machine grants before opening a socket', async () => {
+ discover.mockResolvedValue([])
+ await expect(relay.acquire('machine', 'share', sink as never, closed)).rejects.toBeInstanceOf(SharingEndedError)
+ discover.mockResolvedValue([{ machineId: 'machine', shares: [] }])
+ await expect(relay.acquire('machine', 'share', sink as never, closed)).rejects.toThrow('expired')
+ expect(state.sockets).toHaveLength(0)
+ })
+ it('rejects input, resizing, generic RPCs and grant-management commands on the recipient side', async () => {
+ const { session, ws } = await ready()
+ const count = ws.send.mock.calls.length
+ for (const type of ['terminal_input', 'terminal_resize', 'terminal_paste', 'agent_delete', ...SHARE_REQUEST_TYPES]) {
+ await session.send({ type, payload: { requestId: type } })
+ expect(sink.sendFrame).toHaveBeenLastCalledWith({ type: `${type}_result`, payload: { requestId: type, error: 'VIEW_ONLY' } })
+ }
+ await session.send({ type: 'unknown' })
+ expect(ws.send).toHaveBeenCalledTimes(count)
+ expect(SHARE_RESULT_TYPES).toEqual(new Set([...SHARE_REQUEST_TYPES].map(type => `${type}_result`)))
+ })
+ it('distinguishes revocation from owner disconnects and ignores sends after a transport closes', async () => {
+ const first = await ready()
+ first.ws.emit('close', 4403, Buffer.from('Access removed'))
+ expect(closed).toHaveBeenCalledWith(4403, 'Access removed')
+ first.ws.readyState = 3
+ await first.session.send({ type: 'terminal_alive' })
+ const second = await ready()
+ second.ws.emit('close', 1006, Buffer.alloc(0))
+ expect(closed).toHaveBeenLastCalledWith(1012, 'Owner disconnected')
+ const third = await ready()
+ frame(third.ws, 'observer_closed', { reason: 'Owner disconnected', retry: true })
+ expect(closed).toHaveBeenLastCalledWith(1012, 'Owner disconnected')
+ const fourth = await ready()
+ frame(fourth.ws, 'observer_closed')
+ expect(closed).toHaveBeenLastCalledWith(4403, 'Sharing ended')
+ })
+ it('fails closed on forged identity, malformed frames, and replayed ciphertext', async () => {
+ const first = await begin()
+ const rejected = expect(first.pending).rejects.toThrow('identity')
+ frame(first.ws, 'observer_welcome', { ephemeral: 'forged', signature: 'forged' }); await rejected
+ const second = await ready()
+ frame(second.ws, 'observer_frame', { __e2e: {} })
+ expect(closed).toHaveBeenLastCalledWith(1011, 'Shared harness verification failed')
+ const third = await ready()
+ third.ws.emit('message', Buffer.from('not JSON'))
+ expect(closed).toHaveBeenLastCalledWith(1011, 'The shared harness identity could not be verified.')
+ const fourth = await ready()
+ const packet = fourth.owner.cipher.seal({ type: 'terminal_output', payload: {} })
+ frame(fourth.ws, 'observer_frame', packet); frame(fourth.ws, 'observer_frame', packet)
+ expect(closed).toHaveBeenLastCalledWith(1011, 'Shared harness verification failed')
+ })
+ it('bounds handshake time and releases failures before admission', async () => {
+ const first = await begin()
+ const timed = expect(first.pending).rejects.toThrow('not responding')
+ await vi.advanceTimersByTimeAsync(15_000); await timed
+ const second = await begin(); const error = expect(second.pending).rejects.toThrow('Could not connect')
+ second.ws.emit('error', new Error('offline')); await error
+ const third = await begin(); const revoked = expect(third.pending).rejects.toThrow('Sharing ended')
+ frame(third.ws, 'observer_closed'); await revoked
+ const fourth = await begin(); const offline = expect(fourth.pending).rejects.toThrow('offline')
+ fourth.ws.emit('close', 1006, Buffer.alloc(0)); await offline
+ })
+})
diff --git a/cli/src/sharing/relay.ts b/cli/src/sharing/relay.ts
index 088ffb43e..dcbd8c611 100644
--- a/cli/src/sharing/relay.ts
+++ b/cli/src/sharing/relay.ts
@@ -59,8 +59,9 @@ export class HarnessShareRelay {
cipher = recipientHandshake(ephemeral, machineId, shareId, share.ownerPublicKey, frame.payload)
ready()
} else if (frame.type === 'observer_closed') {
- onClosed(frame.payload?.retry === true ? 1012 : 4403, String(frame.payload?.reason || 'Sharing ended')); detach()
+ onClosed(frame.payload?.retry === true ? 1012 : 4403, String(frame.payload?.reason || 'Sharing ended'))
if (!settled) { clearTimeout(timeout); reject(new Error('Sharing ended')) }
+ detach()
} else if (frame.type === 'observer_frame' && cipher) {
const clear = cipher.open(frame.payload)
if (!clear) { onClosed(1011, 'Shared harness verification failed'); detach(); return }
diff --git a/cli/src/sharing/viewer.ts b/cli/src/sharing/viewer.ts
index 97064ab22..2c4317747 100644
--- a/cli/src/sharing/viewer.ts
+++ b/cli/src/sharing/viewer.ts
@@ -71,6 +71,7 @@ export class ViewerCapture {
})
await new Promise<void>((resolve, reject) => {
this.ws!.once('open', resolve); this.ws!.once('error', () => reject(new Error('The viewer renderer disconnected.')))
+ this.ws!.once('close', () => reject(new Error('The viewer renderer disconnected.')))
})
const page = await this.call('Target.createTarget', { url: 'about:blank' })
const attached = await this.call('Target.attachToTarget', { targetId: page.targetId, flatten: true })
@@ -102,10 +103,10 @@ export class ViewerCapture {
this.closed = true; this.failPending(); this.ws?.terminate(); this.ws = null
const child = this.child; this.child = null
if (child && child.exitCode === null && child.signalCode === null) {
- child.kill('SIGTERM')
await new Promise<void>(resolve => {
const timer = setTimeout(() => { child.kill('SIGKILL'); resolve() }, 3000)
child.once('exit', () => { clearTimeout(timer); resolve() })
+ child.kill('SIGTERM')
})
}
const directory = this.directory; this.directory = null
@@ -129,6 +130,7 @@ export class SharedViewerPool {
try {
const next = viewerTarget(this.target(agentId))
if (next !== current) { await capture?.stop(); capture = null; current = next }
+ if (stopped) return
if (!next) send({ state: 'waiting', message: 'The viewer will appear when this harness produces an output.' })
else {
if (!capture) { send({ state: 'loading' }); capture = this.create(); await capture.start(next) }
diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dart
index 6744bd412..b3f74a344 100644
--- a/desktop/lib/sharing/shared_harness_panel.dart
+++ b/desktop/lib/sharing/shared_harness_panel.dart
@@ -41,6 +41,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
String _viewerMessage = 'Waiting for the live viewer…';
Uint8List? _image;
bool _viewerSelected = false, _ended = false;
+ int _generation = 0;
@override
void initState() {
super.initState();
@@ -48,6 +49,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
}
void _start() {
+ final generation = ++_generation;
final uri = Uri.parse(widget.notifier.config.localCliBaseUrl)
.replace(scheme: 'ws', path: '/api/local-ws');
_terminal = TerminalSession(
@@ -69,9 +71,14 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
transportKind: WsTransportKind.localPlaintext,
localWsUri: uri,
accessTokenProvider: (_, _) async => '',
- onAuthFailure: _end,
- onLocalFailure: (code, reason) => _end(reason),
+ onAuthFailure: (reason) {
+ if (generation == _generation) _end(reason);
+ },
+ onLocalFailure: (code, reason) {
+ if (generation == _generation) _end(reason);
+ },
onEvent: (frame) async {
+ if (generation != _generation) return;
final type = frame['type'] as String,
payload = Map<String, dynamic>.from(frame['payload'] as Map);
if (type == 'observer_viewer') {
@@ -97,7 +104,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
}
},
onStatus: (status) {
- if (!mounted || _ended) return;
+ if (!mounted || _ended || generation != _generation) return;
setState(() {
_status = status;
_failure = null;
@@ -115,6 +122,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
},
);
_connection.onBinaryFrame = (bytes) async {
+ if (generation != _generation) return;
final frame = decodeTerminalLocal(bytes);
if (frame != null && !_ended) await _terminal.handleBinary(frame);
};
@@ -142,6 +150,15 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
super.didUpdateWidget(oldWidget);
if (!widget.hasAccess && !_ended) {
_end('Access removed or invitation expired.');
+ } else if (widget.hasAccess &&
+ (!oldWidget.hasAccess || widget.grant.id != oldWidget.grant.id)) {
+ unawaited(_connection.close());
+ _terminal.dispose();
+ _ended = false;
+ _failure = null;
+ _image = null;
+ _status = ConnectionStatus.connecting;
+ _start();
}
}
diff --git a/desktop/lib/widgets/machine_rail.dart b/desktop/lib/widgets/machine_rail.dart
index 8d9b3215b..4723faa86 100644
--- a/desktop/lib/widgets/machine_rail.dart
+++ b/desktop/lib/widgets/machine_rail.dart
@@ -873,7 +873,7 @@ class _AgentTree extends StatelessWidget {
// nobody finds who does not already know it. Put where a new row would actually appear, it needs no
// discovering. It joins `rows` rather than being appended after the loop so the guide's trunk runs
// down to it and closes there, exactly as it would on a real last agent.
- _NewAgentRow(
+ if (!state.machine.isShared) _NewAgentRow(
notifier: notifier,
machineId: state.machine.machineId,
source: 'rail_tail',
@@ -1054,6 +1054,7 @@ class _AgentRowState extends State<_AgentRow> {
final offlineSelectable =
state.nodeOnline == false && agent.terminalAvailable;
final enabled =
+ (state.machine.isShared && agent.terminalAvailable) ||
offlineSelectable ||
// `connected` never arrives until the local CLI has finished terminating E2EE for this
// machine (or confirmed none is needed, for its own) — no separate readiness check left.
@@ -1082,7 +1083,7 @@ class _AgentRowState extends State<_AgentRow> {
// Right-click opens the SAME menu the ⋯ does. Two menus carrying the same
// two actions in two different shapes is the drift this avoids; the only
// thing lost is opening at the cursor rather than at the button.
- onSecondaryTap: _agentMenu.open,
+ onSecondaryTap: state.machine.isShared ? null : _agentMenu.open,
child: Padding(
// 28px is where a nested row's box starts, which is what the guide's
// arm is drawn to reach (trunk at 19, arm 7 long, stopping 2px short of
diff --git a/desktop/test/share_harness_test.dart b/desktop/test/share_harness_test.dart
new file mode 100644
index 000000000..07ae235a4
--- /dev/null
+++ b/desktop/test/share_harness_test.dart
@@ -0,0 +1,144 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/sharing/share_harness_dialog.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/real_fonts.dart';
+
+void main() {
+ setUpAll(loadRealFonts);
+ Future<void> show(WidgetTester tester, ShareAction manage, {Size size = const Size(900, 800)}) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: RepaintBoundary(key: const Key('sharing-preview'), child: Scaffold(
+ body: Builder(builder: (context) => TextButton(onPressed: () {
+ showDialog<void>(context: context, builder: (_) => ShareHarnessDialog(name: 'Climate dashboard', manage: manage));
+ }, child: const Text('Open share'))),
+ )),
+ ));
+ await tester.tap(find.text('Open share'));
+ await tester.pump(); await tester.pump(const Duration(milliseconds: 300));
+ }
+ Map<String, dynamic> person(String email, {String? error, bool pending = false, bool expired = false, int watching = 0}) => {
+ 'id': email, 'email': email, 'expiresAt': '2026-10-17T00:00:00.000Z',
+ 'error': error, 'pending': pending, 'expired': expired, 'watching': watching,
+ };
+ final submit = find.widgetWithText(FilledButton, 'Share harness');
+
+ testWidgets('invites normalized emails, shows live presence and immediately removes access', (tester) async {
+ var shares = <Map<String, dynamic>>[];
+ final calls = <(String, Map<String, dynamic>)>[];
+ await show(tester, (action, payload) async {
+ calls.add((action, payload));
+ if (action == 'invite') shares = [person('[email protected]', watching: 1), person('[email protected]')];
+ if (action == 'remove') shares.removeWhere((row) => row['id'] == payload['id']);
+ return {'shares': shares};
+ });
+ expect(find.text('Only you have access.'), findsOneWidget);
+ expect(find.text('Can view'), findsOneWidget);
+ await tester.enterText(find.byType(TextField), '[email protected]; [email protected], [email protected]');
+ await tester.tap(submit); await tester.pump();
+ expect(calls.last, ('invite', {'emails': ['[email protected]', '[email protected]'], 'days': 30}));
+ expect(find.text('2 people now have view-only access.'), findsOneWidget);
+ expect(find.text('Watching now · Can view'), findsOneWidget);
+ expect(find.textContaining('Shared with you'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ // Optional artifact for visual review; no golden files or production filesystem writes.
+ final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];
+ if (output != null) {
+ final boundary = tester.firstRenderObject<RenderRepaintBoundary>(find.byType(RepaintBoundary));
+ final image = await boundary.toImage();
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await tester.runAsync(() => File(output).writeAsBytes(png!.buffer.asUint8List()));
+ image.dispose();
+ }
+ await tester.tap(find.widgetWithText(TextButton, 'Remove').first); await tester.pump();
+ expect(calls.last, ('remove', {'id': '[email protected]'}));
+ expect(find.text('[email protected]'), findsNothing);
+ expect(find.text('Access removed.'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 5));
+ expect(calls.last.$1, 'list');
+ await tester.tap(find.text('Done')); await tester.pumpAndSettle();
+ expect(find.text('Share harness'), findsNothing);
+ });
+
+ testWidgets('validates addresses locally and prevents duplicate submissions while saving', (tester) async {
+ final pending = Completer<Map<String, dynamic>>();
+ var invites = 0;
+ await show(tester, (action, _) async {
+ if (action == 'invite') { invites++; return pending.future; }
+ return {'shares': []};
+ });
+ for (final invalid in ['', 'bad', List.generate(21, (i) => '[email protected]').join(',')]) {
+ await tester.enterText(find.byType(TextField), invalid);
+ await tester.tap(submit); await tester.pump();
+ expect(find.textContaining('Enter up to 20 valid'), findsOneWidget);
+ }
+ expect(invites, 0);
+ await tester.enterText(find.byType(TextField), '[email protected]');
+ await tester.tap(submit); await tester.pump();
+ expect(find.text('Saving…'), findsOneWidget);
+ expect(tester.widget<FilledButton>(find.byType(FilledButton)).onPressed, isNull);
+ await tester.pump(const Duration(seconds: 5));
+ expect(invites, 1);
+ pending.complete({'shares': [person('[email protected]', pending: true)]}); await tester.pump();
+ expect(find.text('Waiting for connection'), findsOneWidget);
+ expect(find.textContaining('Invitations saved.'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('renders pending, expired and rejected grants clearly at a narrow width', (tester) async {
+ await show(tester, (_, _) async => {'shares': [
+ person('[email protected]', pending: true), person('[email protected]', expired: true),
+ person('[email protected]', error: 'You already own this harness.'),
+ ]}, size: const Size(440, 680));
+ expect(find.text('Waiting for connection'), findsOneWidget);
+ expect(find.text('Expired · add again to renew'), findsOneWidget);
+ expect(find.text('You already own this harness.'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('shows actionable errors, recovers on retry and survives dismissal during a request', (tester) async {
+ var fails = true;
+ await show(tester, (_, _) async {
+ if (fails) throw const WsRequestFailure(responseType: 'harness_share_list_result', code: 'UNSUPPORTED');
+ return {'shares': []};
+ });
+ expect(find.text('Update Harness on this machine to start sharing.'), findsOneWidget);
+ fails = false;
+ await tester.tap(find.text('Retry')); await tester.pump();
+ expect(find.text('Only you have access.'), findsOneWidget);
+ expect(find.text('Retry'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ final pending = Completer<Map<String, dynamic>>();
+ await show(tester, (_, _) => pending.future);
+ await tester.tap(find.text('Done')); await tester.pumpAndSettle();
+ pending.complete({'shares': []}); await tester.pump();
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('a stale presence refresh cannot erase a newly saved invitation', (tester) async {
+ var lists = 0;
+ final stale = Completer<Map<String, dynamic>>();
+ await show(tester, (action, _) async {
+ if (action == 'list' && ++lists > 1) return stale.future;
+ return {'shares': action == 'invite' ? [person('[email protected]')] : []};
+ });
+ await tester.pump(const Duration(seconds: 5));
+ await tester.enterText(find.byType(TextField), '[email protected]');
+ await tester.tap(submit); await tester.pump();
+ stale.complete({'shares': []}); await tester.pump();
+ expect(find.text('[email protected]'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/docs/plans/2026-09-17-002-share-harness-plan.md b/docs/plans/2026-09-17-002-share-harness-plan.md
index 2c5f71b80..85dc9460c 100644
--- a/docs/plans/2026-09-17-002-share-harness-plan.md
+++ b/docs/plans/2026-09-17-002-share-harness-plan.md
@@ -33,3 +33,19 @@ input/resize/file access, immediate revocation, expiry, reconnect, offline state
viewer updates, and existing owner controls. Measure coverage of the new feature modules and report
the actual numbers. Exercise real sockets and a disposable tmux session as well as desktop widgets;
keep test identities, daemons and runtime data isolated from the user's running sessions.
+
+### Real stack verification
+
+`cli/scripts/share-harness-e2e.ts` runs the production backend and three production daemons against
+disposable MongoDB (replica set) and Redis, with independent fixture accounts and tmux sockets.
+Only the identity provider and model process are deterministic fixtures. Chrome renders an actual
+live viewer. The test checks invitation discovery, two viewers, unchanged owner terminal dimensions,
+blocked input/resize/deletion, changing viewer pixels, reconnect, immediate revocation, offline
+discovery, and durable permissions after restarting the owner daemon.
+
+Run from `cli` with `HARNESS_SHARE_E2E_SERVICES=/path/to/services.json node --import tsx scripts/share-harness-e2e.ts`.
+The JSON contains `mongo` and `redis` URLs for **disposable loopback services**; the test creates a unique
+Mongo database and isolates every daemon, identity, project, browser profile and terminal.
+Set `HARNESS_SHARE_KEEP=1` to retain logs on success. Failure logs are always retained.
+
+This flow passed locally on 2026-09-17 with MongoDB 7.0.15, Redis 7.4.0, tmux and Chrome.