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
feat(sharing): add public/private browser links and encrypted comments
deeb4fabb27b6c7
diff --git a/backend/package.json b/backend/package.jsonindex dd1d9e7e4..e2adfb820 100644--- a/backend/package.json+++ b/backend/package.json@@ -19,7 +19,7 @@"start:local": "concurrently -k -n server,worker -c cyan,magenta \"node dist/server.js\" \"node dist/worker.js\"","test": "NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= vitest run","test:watch": "vitest",- "test:sharing": "NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= vitest run src/routes/harnessShares.test.ts src/lib/observerWs.test.ts --coverage --coverage.include=src/routes/harnessShares.ts --coverage.include=src/lib/observerWs.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100",+ "test:sharing": "NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= vitest run src/routes/harnessShares.test.ts src/routes/harnessLinks.test.ts src/lib/observerWs.test.ts --coverage --coverage.include=src/routes/harnessShares.ts --coverage.include=src/routes/harnessLinks.ts --coverage.include=src/lib/observerWs.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100","postinstall": "prisma generate"},"dependencies": {diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 2cd25dbfa..151410797 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -653,3 +653,23 @@ model HarnessSession {@@index([userId])@@map("harness_sessions")}++/// Public/private link metadata only. The owner daemon keeps the final policy and encrypted discussion.+model HarnessLink {+ id String @id @map("_id")+ ownerId String+ machineId String+ agentId String+ autonomousEnv String+ name String+ engine String?+ ownerPublicKey String+ visibility String+ revokedAt DateTime?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([machineId, agentId])+ @@index([ownerId, machineId])+ @@map("harness_links")+}diff --git a/backend/src/lib/observerWs.test.ts b/backend/src/lib/observerWs.test.tsindex a9fa9f35c..1cef485f5 100644--- a/backend/src/lib/observerWs.test.ts+++ b/backend/src/lib/observerWs.test.ts@@ -2,16 +2,18 @@ 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(),+ upgrade: vi.fn(), link: vi.fn(), profile: vi.fn(),}))vi.mock('./ssoAuth.js', () => ({ authenticateAccessToken: m.auth }))+vi.mock('./prisma.js', () => ({ prisma: { user: { findUnique: m.profile } } }))+vi.mock('../routes/harnessLinks.js', () => ({ recipientLink: m.link }))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' }+const share = { id: '11111111-1111-4111-8111-111111111111', machineId: 'm', agentId: 'a', ownerId: 'owner' }class Socket extends EventEmitter {readyState = 1; bufferedAmount = 0send = vi.fn()@@ -25,7 +27,7 @@ describe('isolated observer WebSocket boundary', () => {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.auth.mockResolvedValue(user); m.grant.mockResolvedValue(share); m.link.mockResolvedValue(share); m.profile.mockResolvedValue({ name: 'Ken' })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 })@@ -34,12 +36,38 @@ describe('isolated observer WebSocket boundary', () => {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('admits anonymous public links, passes only authenticated comment identity and rechecks link access', async () => {+ const socket = { destroyed: false, destroy: vi.fn() }+ const req = (token?: string) => ({ url: `/api/observer-ws?link=${share.id}`, headers: token ? { 'sec-websocket-protocol': token } : {} })+ handleObserverUpgrade(req() as never, socket as never, Buffer.alloc(0)); await flush()+ expect(m.auth).not.toHaveBeenCalled()+ expect(m.link).toHaveBeenCalledWith(share.id, null, 'prod')+ hello(); await flush()+ expect(m.down.mock.calls[0][1].frame.payload).toEqual({ linkId: share.id, email: '', ephemeral: Buffer.alloc(32, 1).toString('base64') })+ m.link.mockResolvedValueOnce(null); changed(); await flush()+ expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))+ ws = new Socket(); m.auth.mockResolvedValue({ ...user, sub: 'owner' }); m.profile.mockResolvedValue(null)+ handleObserverUpgrade(req('owner-token') as never, socket as never, Buffer.alloc(0)); await flush(); hello(); await flush()+ expect(m.down.mock.calls.at(-1)?.[1].frame.payload).toMatchObject({ linkId: share.id,+ authorId: 'owner', authorName: 'Ken', owner: true })+ ws.close(); ws = new Socket(); m.link.mockResolvedValueOnce(null)+ handleObserverUpgrade(req() as never, socket as never, Buffer.alloc(0)); await flush()+ expect(ws.close).toHaveBeenCalledWith(4403, expect.any(String))+ handleObserverUpgrade({ url: '/api/observer-ws?link', headers: {} } as never, socket as never, Buffer.alloc(0)); await flush()+ expect(socket.destroy).toHaveBeenCalled()+ })+ it('does not admit a connection that closed while resolving the commenter name', async () => {+ let release!: (profile: unknown) => void+ m.profile.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))+ const pending = attach(); await flush(); ws.close(); release({ name: 'Ken' }); await pending+ expect(ws.send).not.toHaveBeenCalled()+ })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') },+ type: 'observer_open', payload: { shareId: share.id, email: '[email protected]', authorId: 'ken', authorName: 'Ken', owner: false, ephemeral: Buffer.alloc(32, 1).toString('base64') },} })const connId = m.down.mock.calls[0][1].connIdfor (const type of ['agents', 'message', 'e2e_welcome', 'terminal_ready']) upward({ targetConnId: connId, frame: { type } })diff --git a/backend/src/lib/observerWs.ts b/backend/src/lib/observerWs.tsindex 8b54698c1..9497b0751 100644--- a/backend/src/lib/observerWs.ts+++ b/backend/src/lib/observerWs.ts@@ -7,6 +7,9 @@ import { authenticateAccessToken, type AuthUser } from './ssoAuth.js'import { parseAutonomousEnvironment } from './autonomousEnvironment.js'import { extractKey } from '../utils/crypto.js'import { recipientShare } from '../routes/harnessShares.js'+import { recipientLink } from '../routes/harnessLinks.js'+import type { AutonomousEnvironment } from './autonomousEnvironment.js'+import { prisma } from './prisma.js'import { publishDown, subscribeUp, subscribeShareChanged } from './bus.js'import { guardedSendJson } from './wsSend.js'import { trackSocketLiveness } from './hub.js'@@ -18,20 +21,23 @@ export function handleObserverUpgrade(req: IncomingMessage, socket: Duplex, headvoid (async () => {const token = extractKey(req)const url = new URL(req.url ?? '/', 'http://localhost')- const id = url.searchParams.get('share') ?? ''- if (!token || !/^[a-f0-9-]{36}$/.test(id)) { socket.destroy(); return }- const user = await authenticateAccessToken(token, parseAutonomousEnvironment(url.searchParams.get('autonomousEnv')))- const share = await recipientShare(id, user)+ const linkMode = url.searchParams.has('link')+ const id = url.searchParams.get(linkMode ? 'link' : 'share') ?? ''+ if ((!token && !linkMode) || !/^[a-f0-9-]{36}$/.test(id)) { socket.destroy(); return }+ const autonomousEnv = parseAutonomousEnvironment(url.searchParams.get('autonomousEnv'))+ const user = token ? await authenticateAccessToken(token, autonomousEnv) : null+ const share = linkMode ? await recipientLink(id, user, autonomousEnv) : await recipientShare(id, user!)if (socket.destroyed) returnwss.handleUpgrade(req, socket, head, ws => {if (!share) { ws.close(4403, 'Sharing ended or invitation expired'); return }- void attachObserver(ws, user, share).catch(() => ws.close(1013, 'Sharing temporarily unavailable'))+ void attachObserver(ws, user, share, linkMode ? autonomousEnv : undefined).catch(() => ws.close(1013, 'Sharing temporarily unavailable'))})})().catch(() => { if (!socket.destroyed) socket.destroy() })}/** Separate from the machine hub: no group key, machine inventory, P2P, or generic RPC route. */-export async function attachObserver(ws: WebSocket, user: AuthUser, share: NonNullable<Awaited<ReturnType<typeof recipientShare>>>): Promise<void> {+export async function attachObserver(ws: WebSocket, user: AuthUser | null,+ share: { id: string; machineId: string; ownerId: string }, linkEnv?: AutonomousEnvironment): Promise<void> {const connId = `observer:${randomUUID()}`const send = (frame: unknown) => guardedSendJson(ws, frame, 'must')const disposers: Array<() => void> = [trackSocketLiveness(ws)]@@ -46,7 +52,8 @@ export async function attachObserver(ws: WebSocket, user: AuthUser, share: NonNuws.once('close', close)const check = async () => {try {- if (!await recipientShare(share.id, user)) ws.close(4403, 'Sharing ended or invitation expired')+ const allowed = linkEnv ? await recipientLink(share.id, user, linkEnv) : await recipientShare(share.id, user!)+ if (!allowed) ws.close(4403, 'Sharing ended or invitation expired')} catch { ws.close(1013, 'Sharing temporarily unavailable') }}const timer = setInterval(() => { void check() }, 5000)@@ -66,6 +73,8 @@ export async function attachObserver(ws: WebSocket, user: AuthUser, share: NonNuif (closed) returnawait check()if (ws.readyState !== WebSocket.OPEN) return+ const profile = user ? await prisma.user.findUnique({ where: { id: user.sub }, select: { name: true } }) : null+ if (closed) returnsend({ type: 'observer_connected' })// Each message is bounded before decoding; encrypted content is interpreted only on the owner daemon.let windowStart = Date.now(), count = 0@@ -78,7 +87,9 @@ export async function attachObserver(ws: WebSocket, user: AuthUser, share: NonNuif (!opened && frame.type === 'observer_hello' && typeof frame.payload?.ephemeral === 'string'&& /^[A-Za-z0-9+/]{43}=$/.test(frame.payload.ephemeral)) {opened = true- await down('observer_open', { shareId: share.id, email: user.email.trim().toLowerCase(),+ await down('observer_open', { ...(linkEnv ? { linkId: share.id } : { shareId: share.id }),+ email: user?.email.trim().toLowerCase() ?? '',+ ...(user ? { authorId: user.sub, authorName: profile?.name || user.email.trim().split('@')[0], owner: user.sub === share.ownerId } : {}),ephemeral: frame.payload.ephemeral }).catch(() => ws.close(1013, 'Owner unavailable'))} else if (opened && frame.type === 'observer_frame' && frame.payload?.__e2e) {await down('observer_frame', frame.payload).catch(() => ws.close(1013, 'Owner unavailable'))diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.tsindex 86d9a809c..3b4bcf679 100644--- a/backend/src/middlewares/authMiddleware.ts+++ b/backend/src/middlewares/authMiddleware.ts@@ -64,6 +64,9 @@ export function registerAuthMiddleware(app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {if (shouldSkipAuth(request.url)) returnconst token = bearerToken(request.headers['authorization'])+ // Anonymous public-link discovery only. With a token, authenticate normally so private links+ // and commenting use the real account. Never exempt a mutation or the invitation inventory.+ if (!token && request.method === 'GET' && /^\/api\/shared-agents\/[a-f0-9-]{36}$/.test(request.url.split('?')[0])) returnif (!token) {return reply.code(401).send({ success: false, error: { code: 'UNAUTHORIZED', message: 'Unauthorized' } })}diff --git a/backend/src/routes/harnessLinks.test.ts b/backend/src/routes/harnessLinks.test.tsnew file mode 100644index 000000000..7bf77d70c--- /dev/null+++ b/backend/src/routes/harnessLinks.test.ts@@ -0,0 +1,116 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import { randomUUID } from 'node:crypto'+const m = vi.hoisted(() => ({+ prisma: { harnessLink: { findFirst: vi.fn(), findUnique: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },+ harnessShare: { findFirst: vi.fn() }, machine: { findFirst: vi.fn() } },+ auth: vi.fn(), presence: vi.fn(), changed: vi.fn(),+}))+vi.mock('../lib/prisma.js', () => ({ prisma: m.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))+vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: m.presence, publishShareChanged: m.changed }))+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: m.auth }))+import { harnessLinkRoutes, recipientLink } from './harnessLinks.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 = { ...owner, sub: 'ken', email: ' [email protected] ' }+const id = randomUUID()+const input = { machineId: 'm1', agentId: 'agent-1', name: 'Shared work', engine: 'codex',+ ownerPublicKey: Buffer.alloc(32, 1).toString('base64'), visibility: 'public' }+const link = { ...input, id, ownerId: owner.sub, autonomousEnv: 'prod', revokedAt: null }+const machine = { machineId: 'm1', userId: owner.sub, billingStatus: 'not_required' }+const auth = { authorization: 'Bearer fixture' }+describe('public/private browser links', () => {+ let app: FastifyInstance+ beforeEach(async () => {+ vi.resetAllMocks()+ m.auth.mockResolvedValue(owner)+ m.prisma.harnessLink.findFirst.mockResolvedValue(link)+ m.prisma.harnessLink.updateMany.mockResolvedValue({ count: 1 })+ m.prisma.machine.findFirst.mockResolvedValue(machine)+ m.presence.mockResolvedValue(new Map([['m1', true]]))+ app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, m.auth)+ await app.register(harnessLinkRoutes); await app.ready()+ })+ afterEach(async () => { await app.close() })+ const get = (headers = {}) => app.inject({ method: 'GET', url: `/api/shared-agents/${id}`, headers })+ const put = (payload: unknown = input) => app.inject({ method: 'PUT', url: `/api/harness-links/${id}`, headers: auth, payload: payload as any })+ it('allows only anonymous discovery, returns minimal public metadata, and forbids caching', async () => {+ const response = await get()+ expect(response.statusCode).toBe(200)+ expect(response.headers['cache-control']).toBe('no-store')+ expect(response.json().data).toEqual({ ...input, id, online: true, canComment: false })+ expect(m.auth).not.toHaveBeenCalled()+ expect((await get(auth)).json().data.canComment).toBe(true)+ for (const method of ['PUT', 'DELETE', 'POST'] as const) {+ expect((await app.inject({ method, url: `/api/harness-links/${id}` })).statusCode).toBe(401)+ expect((await app.inject({ method, url: `/api/shared-agents/${id}` })).statusCode).toBe(401)+ }+ m.presence.mockResolvedValue(new Map())+ expect((await get()).json().data.online).toBe(false)+ expect((await get({ 'x-autonomous-env': 'invalid' })).statusCode).toBe(400)+ })+ it('private links reveal nothing to guests or strangers and reuse only exact active email grants', async () => {+ m.prisma.harnessLink.findFirst.mockResolvedValue({ ...link, visibility: 'private' })+ expect((await get()).statusCode).toBe(401)+ m.auth.mockResolvedValue(ken)+ const denied = await get(auth)+ expect(denied.statusCode).toBe(403)+ expect(denied.json()).not.toHaveProperty('data')+ m.prisma.harnessShare.findFirst.mockResolvedValue({ id: 'invitation' })+ expect((await get(auth)).statusCode).toBe(200)+ expect(m.prisma.harnessShare.findFirst).toHaveBeenLastCalledWith({ where: {+ machineId: 'm1', agentId: 'agent-1', ownerId: 'owner', autonomousEnv: 'prod',+ recipientEmail: '[email protected]', revokedAt: null, expiresAt: { gt: expect.any(Date) },+ } })+ m.auth.mockResolvedValue(owner)+ expect((await get(auth)).statusCode).toBe(200)+ m.prisma.harnessShare.findFirst.mockResolvedValue(null)+ expect(await recipientLink(id, ken, 'prod')).toBeNull()+ })+ it('fails closed across deletion, revocation, environments and billing', async () => {+ m.prisma.harnessLink.findFirst.mockResolvedValue(null)+ expect(await recipientLink(id, null, 'prod')).toBeNull()+ expect(m.prisma.harnessLink.findFirst).toHaveBeenCalledWith({ where: { id, autonomousEnv: 'prod', revokedAt: null } })+ m.prisma.harnessLink.findFirst.mockResolvedValue(link)+ expect(await recipientLink(id, { ...ken, autonomousEnv: 'stag' }, 'prod')).toBeNull()+ m.prisma.machine.findFirst.mockResolvedValue(null)+ expect(await recipientLink(id, null, 'prod')).toBeNull()+ m.prisma.machine.findFirst.mockResolvedValue({ ...machine, billingStatus: 'suspended' })+ expect(await recipientLink(id, null, 'prod')).toBeNull()+ })+ it('binds metadata to the signed-in owner and notifies observers of visibility changes', async () => {+ expect((await put()).statusCode).toBe(200)+ expect(m.prisma.harnessLink.upsert).toHaveBeenCalledWith({ where: { id },+ create: { ...link }, update: { ...input, ownerId: owner.sub, autonomousEnv: 'prod', revokedAt: null } })+ m.prisma.harnessLink.findUnique.mockResolvedValue(link)+ expect((await put({ ...input, visibility: 'private' })).statusCode).toBe(200)+ expect(m.changed).toHaveBeenCalledWith(id)+ expect(m.prisma.machine.findFirst).toHaveBeenCalledWith({ where: expect.objectContaining({+ machineId: 'm1', userId: 'owner', autonomousEnv: 'prod', OR: expect.any(Array),+ }) })+ })+ it('rejects other owners, repurposed IDs, suspended/deleted machines, and invalid policy', async () => {+ for (const patch of [{ ownerId: 'stranger' }, { machineId: 'other' }, { agentId: 'other' }, { autonomousEnv: 'stag' }]) {+ m.prisma.harnessLink.findUnique.mockResolvedValue({ ...link, ...patch })+ expect((await put()).statusCode).toBe(403)+ }+ m.prisma.machine.findFirst.mockResolvedValue(null)+ expect((await put()).statusCode).toBe(403)+ m.prisma.machine.findFirst.mockResolvedValue({ ...machine, billingStatus: 'suspended' })+ expect((await put()).statusCode).toBe(403)+ for (const patch of [{ visibility: 'off' }, { ownerPublicKey: 'bad' }, { ownerId: 'spoof' }, { agentId: '' }]) {+ expect((await put({ ...input, ...patch })).statusCode).toBe(400)+ }+ expect(m.prisma.harnessLink.upsert).not.toHaveBeenCalled()+ })+ it('revokes only owner-scoped links; retries cannot revoke someone else’s link', async () => {+ const request = { method: 'DELETE' as const, url: `/api/harness-links/${id}`, headers: auth }+ expect((await app.inject(request)).json().data).toEqual({ removed: true })+ expect(m.prisma.harnessLink.updateMany).toHaveBeenCalledWith({ where: { id, ownerId: 'owner', autonomousEnv: 'prod' }, data: { revokedAt: expect.any(Date) } })+ expect(m.changed).toHaveBeenCalledWith(id)+ m.prisma.harnessLink.updateMany.mockResolvedValue({ count: 0 })+ expect((await app.inject(request)).statusCode).toBe(404)+ })+})diff --git a/backend/src/routes/harnessLinks.ts b/backend/src/routes/harnessLinks.tsnew file mode 100644index 000000000..60b17324f--- /dev/null+++ b/backend/src/routes/harnessLinks.ts@@ -0,0 +1,77 @@+import type { FastifyInstance } from 'fastify'+import { z } from 'zod'+import { prisma, machineAlive } from '../lib/prisma.js'+import { getAgentPresenceMany, publishShareChanged } from '../lib/bus.js'+import { machineBillingAllowsDataPlane } from '../lib/billingState.js'+import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'+import { validateBody, validateParams } from '../middlewares/validation.js'+import { sendError, sendSuccess } from '../utils/response.js'+import type { AuthUser } from '../lib/ssoAuth.js'++const params = z.object({ id: z.string().uuid() })+const body = z.object({+ machineId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), agentId: z.string().min(1).max(160),+ name: z.string().trim().min(1).max(160), engine: z.string().max(64).nullable(),+ ownerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{43}=$/), visibility: z.enum(['public', 'private']),+}).strict()++/** Both HTTP discovery and live observer admission apply this policy. No email list is exposed. */+export async function recipientLink(id: string, user: AuthUser | null, autonomousEnv: AutonomousEnvironment) {+ const link = await prisma.harnessLink.findFirst({ where: { id, autonomousEnv, revokedAt: null } })+ if (!link || user && user.autonomousEnv !== autonomousEnv) return null+ if (link.visibility !== 'public') {+ if (!user) return null+ if (user.sub !== link.ownerId && !await prisma.harnessShare.findFirst({ where: {+ machineId: link.machineId, agentId: link.agentId, ownerId: link.ownerId, autonomousEnv,+ recipientEmail: user.email.trim().toLowerCase(), revokedAt: null, expiresAt: { gt: new Date() },+ } })) return null+ }+ const machine = await prisma.machine.findFirst({ where: {+ machineId: link.machineId, userId: link.ownerId, autonomousEnv, ...machineAlive,+ } })+ return machine && machineBillingAllowsDataPlane(machine) ? link : null+}++export async function harnessLinkRoutes(app: FastifyInstance): Promise<void> {+ // This one GET is optionally authenticated; mutations below retain the global SSO gate.+ app.get<{ Params: z.infer<typeof params> }>('/api/shared-agents/:id',+ { preHandler: validateParams(params) }, async (req, reply) => {+ reply.header('Cache-Control', 'no-store').header('Referrer-Policy', 'no-referrer')+ let autonomousEnv: AutonomousEnvironment+ try { autonomousEnv = parseAutonomousEnvironment(req.headers['x-autonomous-env']) }+ catch { return sendError(reply, 'Invalid Autonomous environment.', 'INVALID_AUTONOMOUS_ENV', 400) }+ const link = await recipientLink(req.params.id, req.user ?? null, autonomousEnv)+ if (!link) return sendError(reply, req.user ? 'This link is unavailable or your email has not been invited.'+ : 'Sign in with an invited email to open a private link.', req.user ? 'FORBIDDEN' : 'SIGN_IN_REQUIRED', req.user ? 403 : 401)+ const presence = await getAgentPresenceMany([link.machineId])+ sendSuccess(reply, { id: link.id, machineId: link.machineId, agentId: link.agentId, name: link.name,+ engine: link.engine, ownerPublicKey: link.ownerPublicKey, visibility: link.visibility,+ online: !!presence.get(link.machineId), canComment: !!req.user })+ })++ app.put<{ Params: z.infer<typeof params>; Body: z.infer<typeof body> }>('/api/harness-links/:id',+ { preHandler: [validateParams(params), validateBody(body)] }, async (req, reply) => {+ const user = req.user!, input = req.body+ const machine = await prisma.machine.findFirst({ where: {+ machineId: input.machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive,+ } })+ if (!machine || !machineBillingAllowsDataPlane(machine)) return sendError(reply, 'This machine is not available to share.', 'FORBIDDEN', 403)+ const old = await prisma.harnessLink.findUnique({ where: { id: req.params.id } })+ if (old && (old.ownerId !== user.sub || old.machineId !== input.machineId || old.agentId !== input.agentId+ || old.autonomousEnv !== user.autonomousEnv)) return sendError(reply, 'This link cannot be changed.', 'FORBIDDEN', 403)+ const data = { ...input, ownerId: user.sub, autonomousEnv: user.autonomousEnv, revokedAt: null }+ await prisma.harnessLink.upsert({ where: { id: req.params.id }, create: { id: req.params.id, ...data }, update: data })+ await publishShareChanged(req.params.id)+ sendSuccess(reply, { id: req.params.id })+ })++ app.delete<{ Params: z.infer<typeof params> }>('/api/harness-links/:id',+ { preHandler: validateParams(params) }, async (req, reply) => {+ const changed = await prisma.harnessLink.updateMany({ where: {+ id: req.params.id, ownerId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv,+ }, data: { revokedAt: new Date() } })+ if (!changed.count) return sendError(reply, 'Link not found.', 'NOT_FOUND', 404)+ await publishShareChanged(req.params.id)+ sendSuccess(reply, { removed: true })+ })+}diff --git a/backend/src/server.ts b/backend/src/server.tsindex f136e117d..07f5b0266 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -10,6 +10,7 @@ import { registerAuthMiddleware } from './middlewares/authMiddleware.js'import { cursorRoutes } from './routes/cursor.js'import { voiceRoutes } from './routes/voice.js'import { harnessShareRoutes } from './routes/harnessShares.js'+import { harnessLinkRoutes } from './routes/harnessLinks.js'import { deskRoutes } from './routes/desk.js'import { handleObserverUpgrade } from './lib/observerWs.js'import { deviceAuthRoutes } from './routes/deviceAuth.js'@@ -164,6 +165,7 @@ async function start(): Promise<void> {await app.register(deviceAuthRoutes) // device-authorization grant: how the desktop app gets a machine keyawait app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registryawait app.register(harnessShareRoutes)+ await app.register(harnessLinkRoutes)await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)// Dedicated public subdomain app-proxy on its own port (Host-header routed → tunnelled to the node app).diff --git a/cli/scripts/share-harness-e2e-preload.cjs b/cli/scripts/share-harness-e2e-preload.cjsnew file mode 100644index 000000000..aedbc2d92--- /dev/null+++ b/cli/scripts/share-harness-e2e-preload.cjs@@ -0,0 +1,12 @@+// Test process only: isolate every default engine/profile directory without changing the caller's+// HOME or CODEX_HOME. Load before the daemon's ESM imports capture os.homedir.+const os = require('node:os');+const { basename, dirname } = require('node:path');+const { realpathSync } = require('node:fs');+const { syncBuiltinESMExports } = require('node:module');+const root = realpathSync(process.env.HARNESS_SHARE_TEST_HOME || '');+if (process.env.NODE_ENV !== 'test' || !basename(dirname(root)).startsWith('harness-share-e2e-')) {+ throw new Error('Sharing fixture requires its own temporary home.');+}+os.homedir = () => root;+syncBuiltinESMExports();diff --git a/cli/scripts/share-harness-e2e.ts b/cli/scripts/share-harness-e2e.tsindex f935693ae..d8676ab12 100644--- a/cli/scripts/share-harness-e2e.ts+++ b/cli/scripts/share-harness-e2e.ts@@ -14,6 +14,8 @@ import { promisify } from 'node:util'import { randomUUID } from 'node:crypto'import { inflateSync } from 'node:zlib'import { WebSocket } from 'ws'+import { b64e, newEphemeral } from '../src/lib/e2ee/core.js'+import { recipientHandshake, type ObserverCipher } from '../src/sharing/crypto.js'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.')@@ -62,17 +64,28 @@ class Peer {readonly binary: TerminalBinaryClear[] = []text = ''; stream = ''; closedCode: number | undefined; private inputSequence = 0private heartbeat: NodeJS.Timeout- constructor(readonly ws: WebSocket) {+ private cipher: ObserverCipher | null = null+ constructor(readonly ws: WebSocket, private readonly observation?: { machineId: string; id: string; ownerPublicKey: string }) {+ const ephemeral = newEphemeral()sockets.push(ws)ws.on('message', (raw, binary) => {- if (binary) {- const frame = decodeTerminalLocal(new Uint8Array(raw as Buffer))+ let clear: any = binary ? null : JSON.parse(raw.toString())+ if (observation && clear?.type === 'observer_connected') {+ ws.send(JSON.stringify({ type: 'observer_hello', payload: { ephemeral: b64e(ephemeral.pub) } })); return+ }+ if (observation && clear?.type === 'observer_welcome') {+ this.cipher = recipientHandshake(ephemeral, observation.machineId, observation.id, observation.ownerPublicKey, clear.payload); return+ }+ if (observation && clear?.type === 'observer_closed') { ws.close(clear.payload.retry ? 1012 : 4403); return }+ if (observation && clear?.type === 'observer_frame') { clear = this.cipher!.open(clear.payload); assert.ok(clear) }+ if (binary || clear?.type === 'observer_binary') {+ const frame = decodeTerminalLocal(binary ? new Uint8Array(raw as Buffer) : Buffer.from(clear.payload.bytes, 'base64'))if (!frame) returnthis.binary.push(frame)this.text += (frame.compressed ? inflateSync(frame.bytes) : Buffer.from(frame.bytes)).toString()this.send('terminal_ack', { streamId: frame.streamId, lastSeq: frame.seq })} else {- const frame = JSON.parse(raw.toString()); this.frames.push(frame)+ const frame = clear; this.frames.push(frame)if (frame.type === 'terminal_ready') { this.stream = frame.payload.streamId; this.inputSequence = 0 }}})@@ -87,12 +100,21 @@ class Peer {await until('local peer admission', () => peer.frames.some(f => f.type === 'connected') || peer.closedCode !== undefined)return peer}+ static async observe(link: { machineId: string; id: string; ownerPublicKey: string }, token?: string) {+ const peer = new Peer(new WebSocket(`${backendUrl.replace('http:', 'ws:')}/api/observer-ws?link=${link.id}`, token ? [token] : undefined), link)+ await until('browser observer admission', () => peer.cipher !== null || 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 }))+ if (this.ws.readyState !== WebSocket.OPEN) return+ const frame = this.observation ? { type: 'observer_frame', payload: this.cipher!.seal({ type, payload }) } : { type, payload }+ this.ws.send(JSON.stringify(frame))}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))+ await until(type, () => this.frames.some(f => f.payload?.requestId === requestId)).catch(async error => {+ await writeFile(join(root, 'rpc-failure.json'), JSON.stringify({ type, requestId, closedCode: this.closedCode, frames: this.frames }, null, 2)); throw error+ })return this.frames.find(f => f.payload?.requestId === requestId)!.payload}async open(agentId: string, cols = 120, rows = 40) {@@ -116,7 +138,8 @@ const sso = createServer((req, res) => {let success = falsetry {await new Promise<void>(resolve => sso.listen(0, '127.0.0.1', resolve))- const [backendPort, proxyPort] = await Promise.all([freePort(), freePort()])+ const backendPort = process.env.HARNESS_SHARE_BACKEND_PORT ? Number(process.env.HARNESS_SHARE_BACKEND_PORT) : await freePort()+ const proxyPort = await 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',@@ -127,7 +150,7 @@ try {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 })+ await writeFile(engine, `#!${process.execPath}\nif (process.argv.includes('--version')) { console.log('codex-cli 1.0.0'); process.exit(0) }\nif (process.argv.includes('--help')) { console.log('--approve-for-me --dangerously-bypass-approvals-and-sandbox --ask-for-approval'); 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',@@ -148,7 +171,12 @@ try {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,+ const env = { PATH: process.env.PATH, TMPDIR: process.env.TMPDIR, LANG: 'en_US.UTF-8',+ NODE_ENV: 'test', HARNESS_SHARE_TEST_HOME: folder, LOG_FRAMES: 'true',+ NODE_OPTIONS: `--require=${join(repo, 'cli/scripts/share-harness-e2e-preload.cjs')}`,+ HARNESS_GRID_BIN: join(folder, 'no-grid'), DISABLE_GRID_INSTALL: 'true',+ GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null',+ 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',@@ -184,6 +212,47 @@ try {}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('Checking browser links and encrypted comments')+ const privateLink = (await owner.rpc('harness_share_link', { agentId, visibility: 'private' })).link+ assert.ok(privateLink.url && !privateLink.pending && !privateLink.error, JSON.stringify(privateLink))+ const discoverUrl = `${backendUrl}/api/shared-agents/${privateLink.id}`+ assert.equal((await fetch(discoverUrl)).status, 401)+ assert.equal((await api(accounts[3], `/api/shared-agents/${privateLink.id}`)).status, 403)+ const linkData = (await api(accounts[1], `/api/shared-agents/${privateLink.id}`)).body.data+ assert.equal(new URLSearchParams(new URL(privateLink.url).hash.slice(1)).get('key'), linkData.ownerPublicKey)+ const refused = await Peer.observe(linkData)+ assert.equal(refused.closedCode, 4403)+ const invited = await Peer.observe(linkData, accounts[1].token)+ await invited.open(agentId)+ const publicLink = (await owner.rpc('harness_share_link', { agentId, visibility: 'public' })).link+ assert.equal(publicLink.url, privateLink.url)+ assert.equal((await fetch(discoverUrl)).status, 200)+ const guest = await Peer.observe(linkData), commenter = await Peer.observe(linkData, accounts[3].token)+ await guest.open(agentId)+ assert.ok(guest.text.includes('owner-before-sharing'))+ assert.equal((await guest.rpc('observer_comment_post', { id: randomUUID(), text: 'anonymous spoof', authorId: 'owner', owner: true })).error, 'COMMENT_REJECTED')+ assert.equal((await guest.rpc('terminal_input', { agentId, data: 'ILLEGAL_PUBLIC_INPUT' })).code, 'VIEW_ONLY')+ const commentId = randomUUID()+ for (let retry = 0; retry < 2; retry++) assert.ok(!(await invited.rpc('observer_comment_post', { id: commentId, text: 'Fixture collaboration' })).error)+ const thread = await guest.rpc('observer_comments')+ assert.equal(thread.comments.length, 1); assert.equal(thread.canComment, false); assert.equal(thread.comments[0].canDelete, false)+ assert.equal((await commenter.rpc('observer_comment_remove', { id: commentId })).error, 'COMMENT_REJECTED')+ async function browserCheck(mode: string) {+ const check = process.env.HARNESS_SHARE_BROWSER_CHECK+ if (!check) return+ const path = join(root, `browser-${mode}.json`)+ await writeFile(path, JSON.stringify({ mode, origin: process.env.HARNESS_SHARE_BROWSER_ORIGIN,+ backendUrl, url: privateLink.url, token: mode === 'denied' ? accounts[3].token : accounts[1].token, root }))+ await exec(process.execPath, [check, path], { env: process.env, timeout: 120_000 })+ console.log(`PASS browser ${mode}`)+ }+ await browserCheck('public')+ await owner.rpc('harness_share_link', { agentId, visibility: 'private' })+ await until('private transition closes uninvited public viewers', () => guest.closedCode === 4403 && commenter.closedCode === 4403)+ assert.equal((await invited.rpc('observer_comments')).comments[0].text, 'Fixture collaboration')+ await browserCheck('private')+ await browserCheck('denied')+ await invited.close()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)@@ -225,13 +294,19 @@ try {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)+ assert.equal((await owner.rpc('harness_share_comments', { agentId })).comments[0].text, 'Fixture collaboration')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)+ await owner.rpc('harness_share_link', { agentId, visibility: 'public' })+ const finalGuest = await Peer.observe(linkData); await finalGuest.open(agentId)+ await owner.rpc('harness_share_link', { agentId, visibility: 'off' })+ await until('stop sharing closes link viewers', () => finalGuest.closedCode === 4403)+ assert.equal((await fetch(discoverUrl)).status, 401)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.')+ console.log('PASS: public/private browser links → encrypted comments and moderation → daemon restart persistence → stop sharing → 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 errordiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0a0c448ea..4e983f630 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -4,6 +4,7 @@ import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/stimport { mutateDsh } from './dsh/service.js'import { HarnessShareOwner } from './sharing/owner.js'import { HarnessGrantStore } from './sharing/grants.js'+import { HarnessCollaborationStore } from './sharing/collaboration.js'import { HarnessShareRelay, type SharedMachineReference } from './sharing/relay.js'import { SharedViewerPool } from './sharing/viewer.js'import { fingerprint as e2eeCoreFingerprint, b64d as e2eeCoreDecode } from './lib/e2ee/core.js'@@ -3625,6 +3626,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {machineId: () => backend.machineId,identity: sharingIdentity.getIdentity(),grants: new HarnessGrantStore(join(env.ADAPTER_DATA_DIR, 'harness-shares.json')),+ collaboration: new HarnessCollaborationStore(join(env.ADAPTER_DATA_DIR, 'harness-collaboration.json')),+ autonomousEnv: env.AUTONOMOUS_ENV,terminals, resolveAgent: (id) => registry.resolve(id),send: (id, type, payload) => backend.sendObserver(id, type, payload),publish: (method, path, body) => proxyBackend(method, path, body),diff --git a/cli/src/sharing/collaboration.spec.ts b/cli/src/sharing/collaboration.spec.tsnew file mode 100644index 000000000..b61b3e028--- /dev/null+++ b/cli/src/sharing/collaboration.spec.ts@@ -0,0 +1,235 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { randomUUID } from 'node:crypto'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { HarnessCollaborationStore, type CommentAuthor } from './collaboration.js'+import { HarnessGrantStore } from './grants.js'+import { HarnessShareOwner, type ShareOwnerDeps } from './owner.js'+import { b64e, newEphemeral, newIdentity } from '../lib/e2ee/core.js'+import { recipientHandshake, type ObserverCipher } from './crypto.js'+import type { RegisteredSession } from '../lib/registry.js'++const alice: CommentAuthor = { id: 'alice', name: 'Alice', owner: false }+const bob: CommentAuthor = { id: 'bob', name: 'Bob', owner: false }+const ownerAuthor: CommentAuthor = { id: 'owner:m', name: 'Owner', owner: true }+const linkInput = { machineId: 'm', agentId: 'a', name: 'Example', engine: 'codex', ownerPublicKey: b64e(newIdentity().pub), visibility: 'private' as const }+describe('durable link policy and comments', () => {+ let root: string, path: string, store: HarnessCollaborationStore+ beforeEach(() => {+ vi.useFakeTimers()+ root = mkdtempSync(join(tmpdir(), 'collaboration-')); path = join(root, 'state.json')+ store = new HarnessCollaborationStore(path)+ })+ afterEach(() => { vi.useRealTimers(); rmSync(root, { recursive: true, force: true }) })+ it('persists one stable link, private/public/off changes, publication status and revision fencing', () => {+ expect(store.active('missing', 'm')).toBeUndefined()+ const first = store.set(linkInput)+ expect(first.pending).toBe(true)+ expect(store.active(first.id, 'other')).toBeUndefined()+ store.set({ ...linkInput, agentId: 'b' })+ const second = store.set({ ...linkInput, visibility: 'public' })+ expect(second.id).toBe(first.id)+ store.published(first, null)+ expect(store.link('m', 'a')?.pending).toBe(true)+ store.published(second, 'Denied')+ expect(store.active(first.id, 'm')).toBeUndefined()+ expect(new HarnessCollaborationStore(path).link('m', 'a')?.error).toBe('Denied')+ const retry = store.set({ ...linkInput, visibility: 'public' })+ store.published(retry, null)+ expect(store.active(first.id, 'm')?.pending).toBe(false)+ const copy = store.links(); copy[0].visibility = 'off'+ expect(store.links()[0].visibility).toBe('private')+ store.set({ ...linkInput, visibility: 'off' })+ expect(store.active(first.id, 'm')).toBeUndefined()+ expect(statSync(path).mode & 0o777).toBe(0o600)+ writeFileSync(path, '{bad')+ expect(() => new HarnessCollaborationStore(path)).toThrow('could not be read')+ writeFileSync(path, JSON.stringify({ links: [{ id: 'bad' }], comments: [] }))+ expect(() => new HarnessCollaborationStore(path)).toThrow('could not be read')+ })+ it('authenticates posting, bounds text, deduplicates retries and exposes no private author IDs', () => {+ const id = randomUUID()+ expect(store.post('m', 'a', null, { id, text: 'hello' })).toContain('Sign in')+ for (const input of [{ id: 'bad', text: 'hello' }, { id, text: '' }, { id, text: 'x'.repeat(4001) }]) {+ expect(store.post('m', 'a', alice, input)).toContain('4,000')+ }+ expect(store.post('m', 'a', alice, { id, text: ' Hello 👋\nWorld ' })).toBeNull()+ expect(store.post('m', 'a', alice, { id, text: 'Hello 👋\nWorld' })).toBeNull()+ for (const [machine, agent, author, text] of [+ ['other', 'a', alice, 'Hello 👋\nWorld'], ['m', 'other', alice, 'Hello 👋\nWorld'],+ ['m', 'a', bob, 'Hello 👋\nWorld'], ['m', 'a', alice, 'different'],+ ] as const) expect(store.post(machine, agent, author, { id, text })).toContain('Try again')+ expect(store.comments('m', 'a', null)).toEqual([{ id, text: 'Hello 👋\nWorld', authorName: 'Alice',+ createdAt: expect.any(String), canDelete: false }])+ expect(store.comments('m', 'a', alice)[0].canDelete).toBe(true)+ expect(store.comments('m', 'a', bob)[0].canDelete).toBe(false)+ expect(store.comments('m', 'a', ownerAuthor)[0].canDelete).toBe(true)+ expect(store.comments('m', 'other', alice)).toEqual([])+ expect(store.comments('other', 'a', alice)).toEqual([])+ expect(new HarnessCollaborationStore(path).comments('m', 'a', alice)).toHaveLength(1)+ })+ it('allows author deletion and owner moderation, scoped to the exact agent, including idempotent retry', () => {+ const id = randomUUID(); store.post('m', 'a', alice, { id, text: 'A' })+ expect(store.remove('m', 'a', null, id)).toContain('own comments')+ expect(store.remove('m', 'a', bob, id)).toContain('own comments')+ expect(store.remove('other', 'a', ownerAuthor, id)).toBeNull()+ expect(store.remove('m', 'other', ownerAuthor, id)).toBeNull()+ expect(store.comments('m', 'a', null)).toHaveLength(1)+ expect(store.remove('m', 'a', alice, id)).toBeNull()+ expect(store.remove('m', 'a', alice, id)).toBeNull()+ store.post('m', 'a', bob, { id: randomUUID(), text: 'B' })+ expect(store.remove('m', 'a', ownerAuthor, store.comments('m', 'a', null)[0].id)).toBeNull()+ expect(store.comments('m', 'a', null)).toEqual([])+ })+ it('limits each account’s posting rate across agents and caps durable thread size', () => {+ for (let i = 0; i < 10; i++) expect(store.post('m', 'a', alice, { id: randomUUID(), text: `${i}` })).toBeNull()+ expect(store.post('m', 'b', alice, { id: randomUUID(), text: 'spam' })).toContain('minute')+ expect(store.post('m', 'a', bob, { id: randomUUID(), text: 'separate' })).toBeNull()+ vi.advanceTimersByTime(60_001)+ expect(store.post('m', 'a', alice, { id: randomUUID(), text: 'allowed again' })).toBeNull()+ const data = JSON.parse(readFileSync(path, 'utf8'))+ data.comments = Array.from({ length: 200 }, () => ({ ...data.comments[0], id: randomUUID() }))+ writeFileSync(path, JSON.stringify(data))+ store = new HarnessCollaborationStore(path, () => Date.now())+ expect(store.post('m', 'a', alice, { id: randomUUID(), text: 'full' })).toContain('thread is full')+ const unicode = { ...data.comments[0], text: '界'.repeat(4000) }+ const count = Math.floor((1024 * 1024 - 100) / (Buffer.byteLength(JSON.stringify(unicode)) + 1))+ data.comments = Array.from({ length: count }, () => ({ ...unicode, id: randomUUID() }))+ writeFileSync(path, JSON.stringify(data)); store = new HarnessCollaborationStore(path)+ expect(count).toBeLessThan(200)+ expect(store.post('m', 'a', alice, { id: randomUUID(), text: unicode.text })).toContain('thread is full')+ })+})++describe('owner link and comment authority', () => {+ let root: string, store: HarnessCollaborationStore, grants: HarnessGrantStore, owner: HarnessShareOwner+ const identity = newIdentity()+ let frames: Array<{ id: string; type: string; payload: any }>+ let deps: ShareOwnerDeps+ beforeEach(() => {+ vi.useFakeTimers(); root = mkdtempSync(join(tmpdir(), 'link-owner-')); frames = []+ store = new HarnessCollaborationStore(join(root, 'collaboration.json'))+ grants = new HarnessGrantStore(join(root, 'grants.json'))+ deps = { machineId: () => 'm', identity, grants, collaboration: store,+ terminals: {} as ShareOwnerDeps['terminals'], now: () => Date.now(),+ resolveAgent: id => ['a', 'b'].includes(id) ? { agentId: id, projectPath: '/tmp/example', engine: 'codex' } as unknown as RegisteredSession : undefined,+ send: vi.fn((id, type, payload) => { frames.push({ id, type, payload }); return true }),+ publish: vi.fn(async () => ({ status: 200, body: {} })),+ }+ owner = new HarnessShareOwner(deps)+ })+ afterEach(async () => { await owner.stop(); vi.useRealTimers(); rmSync(root, { recursive: true, force: true }) })+ const manage = (action: string, payload: Record<string, unknown> = {}) => owner.manage(`harness_share_${action}`, { agentId: 'a', ...payload })+ async function connect(options: Record<string, unknown> = {}, agentId = 'a') {+ const link = store.link('m', agentId)!, ephemeral = newEphemeral(), id = `observer:${randomUUID()}`+ await owner.receive(id, 'observer_open', { linkId: link.id, ephemeral: b64e(ephemeral.pub), ...options })+ const welcome = frames.find(f => f.id === id && f.type === 'observer_welcome')+ return { id, cipher: welcome ? recipientHandshake(ephemeral, 'm', link.id, b64e(identity.pub), welcome.payload) : null }+ }+ async function request(client: { id: string; cipher: ObserverCipher | null }, type: string, payload: Record<string, unknown> = {}) {+ await owner.receive(client.id, 'observer_frame', client.cipher!.seal({ type, payload }) as any)+ }+ function read(client: { id: string; cipher: ObserverCipher | null }) {+ const received = frames.filter(f => f.id === client.id && f.type === 'observer_frame')+ frames = frames.filter(f => f.id !== client.id || f.type !== 'observer_frame')+ return received.map(f => client.cipher!.open(f.payload) as any)+ }+ it('creates a pinned private link, admits only invited accounts or the owner, and counts link watchers', async () => {+ expect(await manage('list')).toMatchObject({ link: null, collaboration: true })+ expect(await manage('link', { visibility: 'invalid' })).toMatchObject({ error: 'INVALID_VISIBILITY' })+ const result = await manage('link', { visibility: 'private' })+ const url = new URL((result.link as any).url)+ expect(url.origin).toBe('https://harness.autonomous.ai')+ expect(new URLSearchParams(url.hash.slice(1)).get('key')).toBe(b64e(identity.pub))+ expect((await connect()).cipher).toBeNull()+ expect((await connect({ email: '[email protected]', authorId: 'stranger' })).cipher).toBeNull()+ expect((await connect({ authorId: 'owner', owner: true })).cipher).not.toBeNull()+ await manage('invite', { emails: ['[email protected]'] })+ const alice = await connect({ email: '[email protected]', authorId: 'alice', authorName: 'Alice' })+ expect(alice.cipher).not.toBeNull()+ expect((await manage('list')).shares).toMatchObject([{ watching: 1 }])+ await manage('remove', { id: grants.all()[0].id })+ expect(frames.find(f => f.id === alice.id && f.type === 'observer_closed')).toBeTruthy()+ })+ it('public visitors observe without identity but cannot post, spoof an author, control, or target another agent', async () => {+ await manage('link', { visibility: 'public' })+ const guest = await connect(), alice = await connect({ authorId: 'alice', authorName: 'Alice', email: '[email protected]' })+ await request(guest, 'observer_comments')+ expect(read(guest)[0].payload).toMatchObject({ comments: [], canComment: false })+ await request(guest, 'observer_comment_post', { id: randomUUID(), text: 'spoof', authorId: 'owner', owner: true })+ expect(read(guest)[0].payload).toMatchObject({ error: 'COMMENT_REJECTED' })+ for (const type of ['terminal_input', 'terminal_resize', 'agent_delete', 'message']) {+ await request(guest, type, { agentId: 'a', data: 'input' })+ expect(read(guest)[0].payload.code).toBe('VIEW_ONLY')+ }+ await request(alice, 'observer_comment_post', { id: randomUUID(), text: 'wrong target', agentId: 'b' })+ expect(read(alice)[0].payload.code).toBe('VIEW_ONLY')+ const id = randomUUID()+ await request(alice, 'observer_comment_post', { id, text: 'Hello', requestId: 'post', authorId: 'owner' })+ expect(read(alice)[0].payload).toMatchObject({ requestId: 'post', canComment: true, comments: [{ id, authorName: 'Alice', canDelete: true }] })+ expect(read(guest)[0].payload.comments).toMatchObject([{ id, canDelete: false }])+ const bob = await connect({ authorId: 'bob' })+ await request(bob, 'observer_comment_remove', { id })+ expect(read(bob)[0].payload).toMatchObject({ error: 'COMMENT_REJECTED' })+ await request(alice, 'observer_comment_remove', { id })+ expect(read(alice)[0].payload.comments).toEqual([])+ expect((await manage('comment_post', { id: randomUUID(), text: 'Owner reply' })).comments).toMatchObject([{ authorName: 'Owner' }])+ const comments = await manage('comments')+ expect(await manage('comment_remove', { id: (comments.comments as any[])[0].id })).toMatchObject({ comments: [] })+ })+ it('private transition, expiry, and stopping all sharing revoke existing observers immediately', async () => {+ await manage('link', { visibility: 'public' })+ await manage('invite', { emails: ['[email protected]'], days: 7 })+ const guest = await connect(), alice = await connect({ email: '[email protected]', authorId: 'alice' })+ await manage('link', { visibility: 'private' })+ expect(frames.find(f => f.id === guest.id && f.type === 'observer_closed')).toBeTruthy()+ expect(frames.find(f => f.id === alice.id && f.type === 'observer_closed')).toBeUndefined()+ vi.setSystemTime(Date.now() + 8 * 86400_000); await vi.advanceTimersByTimeAsync(1000)+ expect(frames.find(f => f.id === alice.id && f.type === 'observer_closed')).toBeTruthy()+ await manage('link', { visibility: 'public' })+ const next = await connect()+ const result = await manage('link', { visibility: 'off' })+ expect(result).toMatchObject({ shares: [], link: { visibility: 'off', url: null } })+ expect(frames.find(f => f.id === next.id && f.type === 'observer_closed')).toBeTruthy()+ expect((await connect()).cipher).toBeNull()+ expect(grants.all().every(g => g.revoked)).toBe(true)+ })+ it('retries offline publication, fails closed on permanent errors, and scopes sync to this machine', async () => {+ vi.mocked(deps.publish).mockRejectedValueOnce(new Error('offline'))+ expect(await manage('link', { visibility: 'public' })).toMatchObject({ link: { pending: true } })+ store.set({ ...linkInput, machineId: 'other' })+ const guest = await connect()+ vi.mocked(deps.publish).mockResolvedValueOnce({ status: 503, body: {} })+ await owner.sync(); expect(store.link('m', 'a')?.pending).toBe(true)+ vi.mocked(deps.publish).mockResolvedValueOnce({ status: 403, body: {} })+ await owner.sync()+ expect(store.link('m', 'a')?.error).toContain('could not be published')+ expect(frames.find(f => f.id === guest.id && f.type === 'observer_closed')).toBeTruthy()+ await manage('link', { visibility: 'private' })+ expect(store.link('m', 'a')?.error).toBeNull()+ vi.mocked(deps.publish).mockResolvedValueOnce({ status: 404, body: {} })+ await manage('link', { visibility: 'off' })+ expect(store.link('m', 'a')?.pending).toBe(false)+ expect(store.link('other', 'a')?.pending).toBe(true)+ })+ it('retains staged link environment, checks owner comments and safely handles unsupported daemons', async () => {+ deps.webOrigin = 'https://example.com'; deps.autonomousEnv = 'stag'+ const result = await manage('link', { visibility: 'public' })+ expect(new URL((result.link as any).url).searchParams.get('env')).toBe('stag')+ const ownerClient = await connect({ authorId: 'owner', owner: true })+ await request(ownerClient, 'observer_comment_post', { id: randomUUID(), text: 'Owner' })+ expect(read(ownerClient)[0].payload.comments).toMatchObject([{ authorName: 'Owner', canDelete: true }])+ await manage('link', { visibility: 'public', agentId: 'b' })+ const otherAgent = await connect({}, 'b')+ await manage('comment_post', { id: randomUUID(), text: 'Scoped reply' })+ expect(read(otherAgent)).toEqual([])+ expect(await manage('comment_post', { id: 'bad', text: '' })).toMatchObject({ error: 'COMMENT_REJECTED' })+ deps.collaboration = undefined+ expect(await manage('comments')).toMatchObject({ error: 'UNSUPPORTED' })+ expect(await manage('link', { visibility: 'public' })).toMatchObject({ error: 'UNSUPPORTED' })+ expect((await connect()).cipher).toBeNull()+ await request(ownerClient, 'observer_comments')+ expect(frames.find(f => f.id === ownerClient.id && f.type === 'observer_closed')).toBeTruthy()+ })+})diff --git a/cli/src/sharing/collaboration.ts b/cli/src/sharing/collaboration.tsnew file mode 100644index 000000000..8be4e86c2--- /dev/null+++ b/cli/src/sharing/collaboration.ts@@ -0,0 +1,96 @@+import { randomUUID } from 'node:crypto'+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { dirname } from 'node:path'+import { z } from 'zod'++const linkSchema = z.object({+ id: z.string().uuid(), machineId: z.string(), agentId: z.string(),+ name: z.string(), engine: z.string().nullable(), ownerPublicKey: z.string(),+ visibility: z.enum(['private', 'public', 'off']),+ revision: z.number().int().positive(), pending: z.boolean(), error: z.string().nullable(),+})+const commentSchema = z.object({+ id: z.string().uuid(), machineId: z.string(), agentId: z.string(),+ authorId: z.string(), authorName: z.string(), text: z.string(), createdAt: z.string().datetime(),+})+const schema = z.object({ links: z.array(linkSchema), comments: z.array(commentSchema) })+export type HarnessLink = z.infer<typeof linkSchema>+export type CommentAuthor = { id: string; name: string; owner: boolean }+export const linkVisibility = z.enum(['private', 'public', 'off'])+const newComment = z.object({ id: z.string().uuid(), text: z.string().trim().min(1).max(4000) })++/** Owner-local authority and discussion history. The relay never stores comment text. */+export class HarnessCollaborationStore {+ private data: z.infer<typeof schema>+ private readonly rates = new Map<string, number[]>()+ constructor(private readonly path: string, private readonly now = () => Date.now()) {+ try { this.data = schema.parse(JSON.parse(readFileSync(path, 'utf8'))) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new Error('The harness collaboration file could not be read.')+ this.data = { links: [], comments: [] }+ }+ }+ private save(next: z.infer<typeof schema>): void {+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })+ const temp = `${this.path}.${randomUUID()}.tmp`+ writeFileSync(temp, JSON.stringify(next), { flag: 'wx', mode: 0o600 })+ renameSync(temp, this.path)+ this.data = next+ }+ links(): HarnessLink[] { return this.data.links.map(l => ({ ...l })) }+ link(machineId: string, agentId: string): HarnessLink | undefined {+ return this.links().find(l => l.machineId === machineId && l.agentId === agentId)+ }+ active(id: string, machineId: string): HarnessLink | undefined {+ return this.links().find(l => l.id === id && l.machineId === machineId && l.visibility !== 'off' && !l.error)+ }+ set(input: Omit<HarnessLink, 'id' | 'revision' | 'pending' | 'error'>): HarnessLink {+ const old = this.link(input.machineId, input.agentId)+ const link = linkSchema.parse({ ...input, id: old?.id ?? randomUUID(), revision: (old?.revision ?? 0) + 1,+ pending: true, error: null })+ this.save({ ...this.data, links: [...this.data.links.filter(l => l.id !== link.id), link] })+ return { ...link }+ }+ published(link: HarnessLink, error: string | null): void {+ this.save({ ...this.data, links: this.data.links.map(l => l.id === link.id && l.revision === link.revision+ ? { ...l, pending: false, error } : l) })+ }+ comments(machineId: string, agentId: string, author: CommentAuthor | null) {+ return this.data.comments.filter(c => c.machineId === machineId && c.agentId === agentId)+ .map(({ id, authorId, authorName, text, createdAt }) => ({ id, authorName, text, createdAt,+ canDelete: !!author && (author.owner || author.id === authorId) }))+ }+ post(machineId: string, agentId: string, author: CommentAuthor | null, input: unknown): string | null {+ if (!author) return 'Sign in to comment.'+ const parsed = newComment.safeParse(input)+ if (!parsed.success) return 'Write a comment between 1 and 4,000 characters.'+ const { id, text } = parsed.data+ const existing = this.data.comments.find(c => c.id === id)+ if (existing) return existing.machineId === machineId && existing.agentId === agentId+ && existing.authorId === author.id && existing.text === text ? null : 'This comment could not be saved. Try again.'+ if (this.comments(machineId, agentId, author).length >= 200) return 'This thread is full. Remove a comment before adding another.'+ const comment = { id, machineId, agentId, authorId: author.id, authorName: author.name,+ text, createdAt: new Date(this.now()).toISOString() }+ const thread = [...this.data.comments.filter(c => c.machineId === machineId && c.agentId === agentId), comment]+ // Bound encoded bytes too: Unicode/JSON escaping can outgrow the encrypted frame limit well+ // before the character/count limits. Leave room for the envelope and per-viewer permissions.+ if (Buffer.byteLength(JSON.stringify(thread)) > 1024 * 1024) return 'This thread is full. Remove a comment before adding another.'+ const now = this.now()+ // Prune inactive authors as well as timestamps so public visitors cannot grow this map forever.+ for (const [key, times] of this.rates) {+ const recent = times.filter(t => t > now - 60_000)+ if (recent.length) this.rates.set(key, recent); else this.rates.delete(key)+ }+ const recent = this.rates.get(author.id) ?? []+ if (recent.length >= 10) return 'Please wait a minute before commenting again.'+ this.save({ ...this.data, comments: [...this.data.comments, comment] })+ this.rates.set(author.id, [...recent, now])+ return null+ }+ remove(machineId: string, agentId: string, author: CommentAuthor | null, id: unknown): string | null {+ const comment = this.data.comments.find(c => c.id === id && c.machineId === machineId && c.agentId === agentId)+ if (!author || (comment && !author.owner && author.id !== comment.authorId)) return 'You can only remove your own comments.'+ if (comment) this.save({ ...this.data, comments: this.data.comments.filter(c => c !== comment) })+ return null+ }+}diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.tsindex a64e10e53..41c9e3d72 100644--- a/cli/src/sharing/owner.ts+++ b/cli/src/sharing/owner.ts@@ -6,13 +6,17 @@ import { encodeTerminalLocal } from '../lib/terminalBinary.js'import { TerminalStreamManager } from '../lib/terminalStreamManager.js'import { HarnessGrantStore, inviteSchema, type HarnessGrant } from './grants.js'import { ownerHandshake, type ObserverCipher } from './crypto.js'+import { HarnessCollaborationStore, linkVisibility, type CommentAuthor } from './collaboration.js'type Payload = Record<string, unknown>-interface Observer { grant: HarnessGrant; cipher: ObserverCipher }+interface Observer { grant: HarnessGrant; cipher: ObserverCipher; linkId?: string; author: CommentAuthor | null }export interface ShareOwnerDeps {machineId: () => stringidentity: Identitygrants: HarnessGrantStore+ collaboration?: HarnessCollaborationStore+ webOrigin?: string+ autonomousEnv?: stringterminals: TerminalBackendCoordinatorresolveAgent: (id: string) => RegisteredSession | undefinedsend: (connId: string, type: string, payload: Payload) => boolean@@ -51,9 +55,21 @@ export class HarnessShareOwner {this.timer.unref()}private authorized(observer: Observer): boolean {+ if (observer.linkId) {+ const link = this.deps.collaboration?.active(observer.linkId, this.deps.machineId())+ return !!link && !!this.deps.resolveAgent(link.agentId) && (link.visibility === 'public'+ || observer.author?.owner === true || this.invited(link.agentId, observer.grant.recipientEmail))+ }return !!this.deps.grants.active(observer.grant.id, observer.grant.recipientEmail, this.deps.machineId())&& !!this.deps.resolveAgent(observer.grant.agentId)}+ private invited(agentId: string, email: string): boolean {+ return this.deps.grants.list(this.deps.machineId(), agentId)+ .some(g => !!this.deps.grants.active(g.id, email, this.deps.machineId()))+ }+ private recheck(): void {+ for (const [id, observer] of this.observers) if (!this.authorized(observer)) this.close(id, 'Access removed')+ }private send(connId: string, frame: Payload): boolean {const observer = this.observers.get(connId)if (!observer || !this.authorized(observer)) return false@@ -74,13 +90,24 @@ export class HarnessShareOwner {if (type === 'observer_close') { this.close(connId); return }if (type === 'observer_open') {if (this.observers.has(connId)) { this.close(connId, 'Invalid observer handshake'); return }- const grant = this.deps.grants.active(String(payload.shareId), String(payload.email), this.deps.machineId())+ const link = typeof payload.linkId === 'string'+ ? this.deps.collaboration?.active(payload.linkId, this.deps.machineId()) : undefined+ const email = typeof payload.email === 'string' ? payload.email : ''+ // Identity comes from the authenticated observer relay, never from an encrypted client frame.+ const author = typeof payload.authorId === 'string' && payload.authorId.length > 0 ? {+ id: payload.owner === true ? `owner:${this.deps.machineId()}` : payload.authorId,+ name: payload.owner === true ? 'Owner' : String(payload.authorName || 'Harness user').slice(0, 80),+ owner: payload.owner === true,+ } : null+ const grant: HarnessGrant | null = link && (link.visibility === 'public' || author?.owner || this.invited(link.agentId, email))+ ? { ...link, recipientEmail: email, createdAt: '', expiresAt: '', revoked: false, publicationError: null }+ : payload.linkId ? null : this.deps.grants.active(String(payload.shareId), email, this.deps.machineId())if (!grant || !this.deps.resolveAgent(grant.agentId) || this.observers.size >= 100) {this.deps.send(connId, 'observer_closed', { reason: 'Sharing ended or invitation expired' }); return}try {const { cipher, welcome } = ownerHandshake(this.deps.identity, grant.machineId, grant.id, String(payload.ephemeral))- this.observers.set(connId, { grant, cipher })+ this.observers.set(connId, { grant, cipher, author, ...(link ? { linkId: link.id } : {}) })if (!this.deps.send(connId, 'observer_welcome', welcome)) this.close(connId)} catch { this.deps.send(connId, 'observer_closed', { reason: 'Invalid observer handshake' }) }return@@ -94,12 +121,18 @@ export class HarnessShareOwner {}const p = frame.payload as Payloadconst allowed = ['terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack',- 'terminal_resync', 'terminal_close', 'observer_viewer']+ 'terminal_resync', 'terminal_close', 'observer_viewer', 'observer_comments', 'observer_comment_post', 'observer_comment_remove']if (!allowed.includes(frame.type) || (p.agentId !== undefined && p.agentId !== observer.grant.agentId)|| (frame.type === 'terminal_open' && p.agentId !== observer.grant.agentId)) {this.send(connId, { type: 'terminal_error', payload: { requestId: p.requestId, code: 'VIEW_ONLY' } })return}+ if (frame.type.startsWith('observer_comment')) {+ const result = this.comments(frame.type.replace('observer_', ''), observer.grant.agentId, observer.author, p)+ this.send(connId, { type: 'observer_comments', payload: { ...result, requestId: p.requestId } })+ if (!result.error && frame.type !== 'observer_comments') this.broadcastComments(observer.grant.agentId)+ return+ }if (frame.type === 'observer_viewer') {if (!this.viewers.has(connId) && this.deps.watchViewer) {this.viewers.set(connId, this.deps.watchViewer(observer.grant.agentId,@@ -121,7 +154,25 @@ export class HarnessShareOwner {const session = this.deps.resolveAgent(agentId)if (!session) return { error: 'HARNESS_NOT_FOUND', detail: 'This harness is no longer available.' }const machineId = this.deps.machineId()- if (type === 'harness_share_invite') {+ if (type.startsWith('harness_share_comment')) {+ const result = this.comments(type.replace('harness_share_', ''), agentId,+ { id: `owner:${machineId}`, name: 'Owner', owner: true }, payload)+ if (!result.error && type !== 'harness_share_comments') this.broadcastComments(agentId)+ return result+ }+ if (type === 'harness_share_link') {+ const visibility = linkVisibility.safeParse(payload.visibility)+ if (!this.deps.collaboration) return { error: 'UNSUPPORTED' }+ if (!visibility.success) return { error: 'INVALID_VISIBILITY', detail: 'Choose Public or Private.' }+ this.deps.collaboration.set({ machineId, agentId, visibility: visibility.data,+ name: projectDisplayName(session), engine: session.engine, ownerPublicKey: b64e(this.deps.identity.pub) })+ if (visibility.data === 'off') {+ for (const grant of this.deps.grants.list(machineId, agentId)) this.deps.grants.revoke(grant.id, machineId, agentId)+ }+ this.recheck()+ await this.syncing+ await this.sync()+ } else if (type === 'harness_share_invite') {const parsed = inviteSchema.safeParse(payload)if (!parsed.success) return { error: 'INVALID_INVITATION', detail: 'Enter valid email addresses and choose an expiry.' }for (const email of new Set(parsed.data.emails)) {@@ -137,15 +188,40 @@ export class HarnessShareOwner {return { error: 'INVITATION_NOT_FOUND', detail: 'This invitation is no longer available.' }}for (const [id, observer] of this.observers) if (observer.grant.id === payload.id) this.close(id, 'Access removed')+ this.recheck()await this.syncingawait this.sync()} else if (type !== 'harness_share_list') return { error: 'UNSUPPORTED' }- return { shares: this.deps.grants.list(machineId, agentId).map(grant => ({+ const link = this.deps.collaboration?.link(machineId, agentId)+ let url: string | null = null+ if (link && link.visibility !== 'off') {+ const address = new URL(`/s/${link.id}`, this.deps.webOrigin ?? 'https://harness.autonomous.ai')+ if (this.deps.autonomousEnv && this.deps.autonomousEnv !== 'prod') address.searchParams.set('env', this.deps.autonomousEnv)+ address.hash = new URLSearchParams({ key: link.ownerPublicKey }).toString()+ url = address.toString()+ }+ return { ...(this.deps.collaboration ? { link: link ? { id: link.id, visibility: link.visibility,+ pending: link.pending, error: link.error, url } : null, collaboration: true } : {}),+ shares: this.deps.grants.list(machineId, agentId).map(grant => ({id: grant.id, email: grant.recipientEmail, expiresAt: grant.expiresAt,expired: Date.parse(grant.expiresAt) <= this.now(), pending: grant.pending, error: grant.publicationError,- watching: [...this.observers.values()].filter(o => o.grant.id === grant.id).length,+ watching: [...this.observers.values()].filter(o => o.grant.agentId === agentId && o.grant.recipientEmail === grant.recipientEmail).length,})) }}+ private comments(action: string, agentId: string, author: CommentAuthor | null, payload: Payload): Payload {+ const store = this.deps.collaboration+ if (!store) return { error: 'UNSUPPORTED', detail: 'Update Harness on the owner machine to use comments.' }+ const machineId = this.deps.machineId()+ const error = action === 'comment_post' ? store.post(machineId, agentId, author, payload)+ : action === 'comment_remove' ? store.remove(machineId, agentId, author, payload.id) : null+ return error ? { error: 'COMMENT_REJECTED', detail: error }+ : { comments: store.comments(machineId, agentId, author), canComment: author !== null }+ }+ private broadcastComments(agentId: string): void {+ for (const [id, observer] of this.observers) if (observer.grant.agentId === agentId) {+ this.send(id, { type: 'observer_comments', payload: this.comments('comments', agentId, observer.author, {}) })+ }+ }sync(): Promise<void> {if (this.syncing) return this.syncingconst run = async () => {@@ -168,6 +244,19 @@ export class HarnessShareOwner {}} catch { /* Persisted pending change is retried, including after daemon restart. */ }}+ const store = this.deps.collaboration+ for (const link of store?.links().filter(l => l.pending && l.machineId === this.deps.machineId()) ?? []) {+ try {+ const result = await this.deps.publish(link.visibility === 'off' ? 'DELETE' : 'PUT', `/api/harness-links/${link.id}`,+ link.visibility === 'off' ? undefined : { machineId: link.machineId, agentId: link.agentId,+ name: link.name, engine: link.engine, ownerPublicKey: link.ownerPublicKey, visibility: link.visibility })+ if (result.status >= 200 && result.status < 300 || link.visibility === 'off' && result.status === 404) store!.published(link, null)+ else if (link.visibility !== 'off' && [400, 403, 409, 422].includes(result.status)) {+ store!.published(link, 'The link could not be published. Try saving its access setting again.')+ this.recheck()+ }+ } catch { /* Owner policy is already durable. Retry metadata publication after reconnect. */ }+ }}this.syncing = run().finally(() => { this.syncing = null })return this.syncingdiff --git a/cli/src/sharing/protocol.ts b/cli/src/sharing/protocol.tsindex 8c0bc2ded..6e83e2d6c 100644--- a/cli/src/sharing/protocol.ts+++ b/cli/src/sharing/protocol.ts@@ -1,3 +1,4 @@/** Application extension; the byte-identical E2EE cryptographic core remains unchanged. */-export const SHARE_REQUEST_TYPES = new Set(['harness_share_list', 'harness_share_invite', 'harness_share_remove'])+export const SHARE_REQUEST_TYPES = new Set(['harness_share_list', 'harness_share_invite', 'harness_share_remove',+ 'harness_share_link', 'harness_share_comments', 'harness_share_comment_post', 'harness_share_comment_remove'])export const SHARE_RESULT_TYPES = new Set([...SHARE_REQUEST_TYPES].map(type => `${type}_result`))diff --git a/cli/src/sharing/relay.ts b/cli/src/sharing/relay.tsindex cdff5e2fb..d3ab1e4d3 100644--- a/cli/src/sharing/relay.ts+++ b/cli/src/sharing/relay.ts@@ -83,7 +83,7 @@ export class HarnessShareRelay {// The owner repeats this check after decrypting. Restrict here too so a local client cannot// accidentally send terminal responses, resize events or pasted data into an observer stream.if (!['terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack', 'terminal_resync',- 'terminal_close', 'observer_viewer'].includes(String(frame.type))) {+ 'terminal_close', 'observer_viewer', 'observer_comments', 'observer_comment_post', 'observer_comment_remove'].includes(String(frame.type))) {sink.sendFrame({ type: `${String(frame.type)}_result`, payload: {requestId: (frame.payload as { requestId?: unknown })?.requestId, error: 'VIEW_ONLY',} }); returndiff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 3bc46eaf0..fab5a0880 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -103,8 +103,14 @@ PKCE transaction; conditional adapters handle storage and native-only services.`platform_auth_web.dart` serializes shared login/refresh/logout with Web Locksand reloads other tabs when the account changes. Auth and E2EE keys persist inorigin-local storage; only the OAuth transaction is in session storage.-Private shared sessions use `ObserverRelayCodec` and `/api/observer-ws`, verifying-the owner and permitting only observation. Anonymous public pages are not included.+Shared sessions use `ObserverRelayCodec` and `/api/observer-ws`, verifying the+owner and permitting only observation and authenticated comments. `/s/:id#key=…`+opens `SharedAgentPage` without restoring the visitor's workspace. Public links+allow anonymous viewing; private links require an invited account. Preserve the+fragment identity pin through sign-in and reload: `startHarness` disables Flutter+hash routing, while the sign-in adapter owns the callback and return URL.+The owner daemon stores comments and enforces link/invitation access on every+request. Reuse `ShareHarnessDialog` and `HarnessComments` for both app targets.See [README.md](README.md#web-development) for origin setup, browser storagelifetime, capability limits, and Chrome checks. Browser tests must set`--dart-define=HARNESS_TEST=true` so no production pollers or analytics run.diff --git a/desktop/README.md b/desktop/README.mdindex 4043267c0..6dd793772 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -71,9 +71,14 @@ For a local production build, run `bash scripts/build-web-release.sh X.Y.Z`.- Authenticated access to existing machines uses the shared viewer services andencrypted relay. Link a machine from the browser before controlling it.-- Existing account-bound sharing invitations open read-only through the observer- relay, with the owner's identity verified. Public, anonymous session URLs and- published snapshots are the next product layer; they are not implemented here.+- **Share** on an agent creates one browser link. Private links require sign-in+ with an invited email; public links open without an account. Viewers receive+ only that agent's read-only output through the encrypted observer relay, with+ the owner's identity pinned in the link. Sign-in returns to the same link.+ Comments travel through that channel and persist on the owner's machine;+ posting requires sign-in. Authors can remove their comments and owners can+ moderate the thread. **Stop sharing** removes link and invitation access.+ The owner's machine must be online; published snapshots are not included.- Login, linked machines, preferences, and cached workspace metadata persist inthis origin's local storage across tabs and browser restarts. Only the pendingOAuth transaction is tab-local. Browser locks serialize token refresh anddiff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex 38c602657..6720627df 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart'show kIsWeb, LicenseRegistry, LicenseEntryWithLineBreaks;import 'package:flutter/services.dart';import 'package:flutter_riverpod/flutter_riverpod.dart';+import 'package:flutter_web_plugins/url_strategy.dart';import 'analytics/analytics_lifecycle.dart';import 'core/crash_log.dart';@@ -31,6 +32,8 @@ import 'shortcuts/keyboard_practice.dart';import 'widgets/shortcuts_sheet.dart';import 'widgets/update_notice.dart';import 'widgets/window_chrome.dart';+import 'sharing/shared_agent_location.dart';+import 'sharing/shared_agent_page.dart';/// The screen an app puts up once someone is signed in — the desktop's swarm of/// panes, or the phone's one-agent-at-a-time shell. It is the only thing the two@@ -53,6 +56,9 @@ Future<void> startHarness({/// [TerminalTransportPlugin]); the desktop passes none.TerminalTransportPluginFactory? transportPlugins,}) async {+ // Share links and OAuth own the browser URL. Flutter's default hash routing would+ // erase the share's pinned identity on the first navigation or window resize.+ if (kIsWeb) setUrlStrategy(null);WidgetsFlutterBinding.ensureInitialized();LicenseRegistry.addLicense(() async* {yield LicenseEntryWithLineBreaks([@@ -174,10 +180,12 @@ class RootShell extends ConsumerStatefulWidget {class _RootShellState extends ConsumerState<RootShell>with WidgetsBindingObserver {bool _menuDialogOpen = false;+ SharedAgentLocation? _sharedLocation;@overridevoid initState() {super.initState();+ if (kIsWeb) _sharedLocation = SharedAgentLocation.parse(Uri.base);WidgetsBinding.instance.addObserver(this);_appMenuChannel.setMethodCallHandler(_onAppMenu);}@@ -246,7 +254,7 @@ class _RootShellState extends ConsumerState<RootShell>return ListenableBuilder(listenable: app,builder: (context, _) {- final Widget screen;+ Widget screen;switch (app.status) {case AppStatus.bootstrapping:// `bootstrapping` covers two unrelated moments: the app starting@@ -276,6 +284,12 @@ class _RootShellState extends ConsumerState<RootShell>case AppStatus.authenticated:screen = widget.authenticatedScreen(app);}+ // Preserve the fragment pin while dialogs navigate; an OAuth callback can restore it later.+ if (kIsWeb) _sharedLocation ??= SharedAgentLocation.parse(Uri.base);+ final shared = _sharedLocation;+ if (shared != null) {+ screen = SharedAgentPage(app: app, location: shared);+ }// Only the home shell carries its own drag handle and traffic-light// clearance (the rail's head). Every other screen fills the window// with a centred card, so the strip goes over it here, once, insteaddiff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex 2ce7afe0a..7cfb758f6 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -16,6 +16,10 @@ const Set<String> encryptedDownTypes = {'harness_share_list','harness_share_invite','harness_share_remove',+ 'harness_share_link',+ 'harness_share_comments',+ 'harness_share_comment_post',+ 'harness_share_comment_remove',// Harness's application RPC extensions (CLI e2ee/applicationFrames.ts).'grid_fleet_capabilities','grid_fleet_run',diff --git a/desktop/lib/sharing/harness_comments.dart b/desktop/lib/sharing/harness_comments.dartnew file mode 100644index 000000000..90d435f2f--- /dev/null+++ b/desktop/lib/sharing/harness_comments.dart@@ -0,0 +1,264 @@+import 'dart:async';+import 'dart:math';++import 'package:flutter/material.dart';++import '../terminal/terminal_text.dart';+import '../widgets/terminal_text_action.dart';+import '../ws/ws_conn.dart';++typedef CommentAction = Future<Map<String, dynamic>> Function(+ String action,+ Map<String, dynamic> payload,+);++/// One discussion UI for the owner and observers. Authorization is always repeated by the owner.+class HarnessComments extends StatefulWidget {+ const HarnessComments({+ super.key,+ required this.manage,+ this.updates,+ this.onSignIn,+ });+ final CommentAction manage;+ final Listenable? updates;+ final VoidCallback? onSignIn;+ @override+ State<HarnessComments> createState() => _HarnessCommentsState();+}++class _HarnessCommentsState extends State<HarnessComments> {+ final _text = TextEditingController();+ List<Map<String, dynamic>> _comments = [];+ bool _loading = true, _refreshing = false, _busy = false, _canComment = false;+ int _revision = 0;+ String? _error, _postId, _postText;+ Timer? _timer;++ @override+ void initState() {+ super.initState();+ widget.updates?.addListener(_refresh);+ _refresh();+ _timer = Timer.periodic(const Duration(seconds: 5), (_) => _refresh());+ }++ @override+ void didUpdateWidget(HarnessComments oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.updates != widget.updates) {+ oldWidget.updates?.removeListener(_refresh);+ widget.updates?.addListener(_refresh);+ }+ }++ @override+ void dispose() {+ _timer?.cancel();+ widget.updates?.removeListener(_refresh);+ _text.dispose();+ super.dispose();+ }++ String _message(Object error) =>+ error is WsRequestFailure && error.detail != null+ ? error.detail!+ : 'Could not reach the owner. Your draft is saved here; try again.';+ void _accept(Map<String, dynamic> data) {+ if (data['error'] != null) {+ throw WsRequestFailure(+ responseType: 'comments',+ code: '${data['error']}',+ detail: data['detail'] as String?,+ );+ }+ _comments = [+ for (final c in data['comments'] as List? ?? [])+ Map<String, dynamic>.from(c as Map),+ ];+ _canComment = data['canComment'] == true;+ _loading = false;+ }++ void _refresh() {+ unawaited(_load());+ }++ Future<void> _load() async {+ if (_refreshing || _busy) return;+ _refreshing = true;+ final revision = _revision;+ try {+ final data = await widget.manage('comments', {});+ if (mounted && revision == _revision) {+ setState(() {+ _accept(data);+ _error = null;+ });+ }+ } catch (error) {+ if (mounted && revision == _revision) {+ setState(() {+ _loading = false;+ _error = _message(error);+ });+ }+ } finally {+ _refreshing = false;+ }+ }++ static String _uuid() {+ final random = Random.secure();+ final bytes = List.generate(16, (_) => random.nextInt(256));+ bytes[6] = (bytes[6] & 15) | 64;+ bytes[8] = (bytes[8] & 63) | 128;+ final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();+ return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';+ }++ Future<void> _act(String action, Map<String, dynamic> payload) async {+ if (_busy) return;+ setState(() {+ _busy = true;+ _revision++;+ _error = null;+ });+ try {+ final data = await widget.manage(action, payload);+ if (mounted) {+ setState(() {+ _accept(data);+ if (action == 'comment_post') {+ _text.clear();+ _postId = null;+ _postText = null;+ }+ });+ }+ } catch (error) {+ if (mounted) setState(() => _error = _message(error));+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }++ void _post() {+ final text = _text.text.trim();+ if (text.isEmpty || !_canComment || _busy) return;+ if (_postText != text) {+ _postText = text;+ _postId = _uuid();+ }+ unawaited(_act('comment_post', {'id': _postId, 'text': text}));+ }++ @override+ Widget build(BuildContext context) {+ final cell = terminalCellSizeOf(context);+ final style = terminalContentStyle(+ color: DefaultTextStyle.of(context).style.color,+ );+ return DefaultTextStyle(+ style: style,+ child: Padding(+ padding: EdgeInsets.all(cell.width * 2),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ 'Comments${_comments.isEmpty ? '' : ' (${_comments.length})'}',+ ),+ SizedBox(height: cell.height),+ Expanded(+ child: _loading+ ? const Text('Loading comments…')+ : _comments.isEmpty+ ? const Text('Start the conversation.')+ : ListView.separated(+ itemCount: _comments.length,+ separatorBuilder: (_, _) => SizedBox(height: cell.height),+ itemBuilder: (context, index) {+ final c = _comments[index];+ final date = DateTime.tryParse('${c['createdAt']}')+ ?.toLocal();+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ '${c['authorName']}',+ overflow: TextOverflow.ellipsis,+ style: style.copyWith(+ fontWeight: FontWeight.bold,+ ),+ ),+ ),+ if (date != null)+ Text(+ '${date.month}/${date.day} ${date.hour}:${date.minute.toString().padLeft(2, '0')}',+ ),+ if (c['canDelete'] == true)+ TerminalTextAction(+ label: 'Remove',+ onPressed: _busy+ ? null+ : () => _act('comment_remove', {+ 'id': c['id'],+ }),+ ),+ ],+ ),+ SelectionArea(+ child: Text('${c['text']}', style: style),+ ),+ ],+ );+ },+ ),+ ),+ if (_error != null)+ Semantics(liveRegion: true, child: Text(_error!)),+ SizedBox(height: cell.height),+ if (_canComment) ...[+ TextField(+ key: const Key('comment-input'),+ controller: _text,+ readOnly: _busy,+ style: style,+ minLines: 1,+ maxLines: 3,+ maxLength: 4000,+ decoration: InputDecoration(+ hintText: 'Leave a comment…',+ hintStyle: style,+ border: InputBorder.none,+ filled: false,+ contentPadding: EdgeInsets.zero,+ counterText: '',+ ),+ onChanged: (_) => setState(() {}),+ ),+ Align(+ alignment: Alignment.centerRight,+ child: TerminalTextAction(+ label: _busy ? 'Saving…' : 'Comment',+ onPressed: _busy || _text.text.trim().isEmpty ? null : _post,+ ),+ ),+ ] else if (widget.onSignIn != null)+ Align(+ alignment: Alignment.centerLeft,+ child: TerminalTextAction(+ label: 'Sign in to comment',+ onPressed: widget.onSignIn,+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dartindex 46398fa12..b611c8e9a 100644--- a/desktop/lib/sharing/share_harness_dialog.dart+++ b/desktop/lib/sharing/share_harness_dialog.dart@@ -1,13 +1,17 @@import 'dart:async';-import '../shared/widgets/labeled_field.dart';+import 'package:flutter/services.dart';import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;-import '../shared/widgets/app_dialog.dart';-import '../shared/widgets/app_select_field.dart';-import '../shared/widgets/skeleton.dart';+import '../terminal/terminal_text.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';+import '../widgets/box_chrome.dart';+import '../widgets/terminal_prompt.dart';+import '../widgets/terminal_text_action.dart';+import 'harness_comments.dart';import '../state/app_state.dart';import '../ws/ws_conn.dart';@@ -22,8 +26,8 @@ Future<void> showShareHarnessDialog(String machineId,String agentId,String name,-) => showAppDialog<void>(- context: context,+) => showTerminalPrompt<void>(+ context,builder: (_) => ShareHarnessDialog(name: name,manage: (action, payload) =>@@ -49,6 +53,8 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {bool _loading = true, _busy = false;String? _error, _notice;int _days = 30;+ Map<String, dynamic>? _link;+ bool _collaboration = false, _comments = false, _manualCopy = false;Timer? _presence;int _revision = 0;bool _refreshing = false;@@ -75,6 +81,10 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {? error.detail!: 'Could not reach this harness. Check the connection and try again.';void _accept(Map<String, dynamic> response) {+ _collaboration = response['collaboration'] == true;+ _link = response['link'] is Map+ ? Map<String, dynamic>.from(response['link'] as Map)+ : null;_shares = [for (final row in response['shares'] as List? ?? const [])Map<String, dynamic>.from(row as Map),@@ -175,181 +185,351 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {}}+ Future<void> _linkAction(String visibility, {bool copy = false}) async {+ if (_busy) return;+ setState(() {+ _busy = true;+ _revision++;+ _error = null;+ _notice = null;+ });+ try {+ if (!copy || _link == null || _link?['visibility'] == 'off') {+ _accept(await widget.manage('link', {'visibility': visibility}));+ }+ if (copy && _link?['pending'] != true && _link?['error'] == null) {+ final url = _link?['url'] as String?;+ if (url == null) throw StateError('Link unavailable');+ await Clipboard.setData(ClipboardData(text: url));+ _manualCopy = false;+ if (mounted) setState(() => _notice = 'Link copied.');+ } else if (mounted) {+ setState(+ () => _notice =+ _link?['error'] as String? ??+ (_link?['pending'] == true+ ? 'Saved. Waiting for the connection before the link is ready.'+ : visibility == 'off'+ ? 'Sharing stopped.'+ : 'Access updated.'),+ );+ }+ } catch (error) {+ _manualCopy = copy && _link?['url'] != null;+ if (mounted) {+ setState(+ () => _error = copy && _link?['url'] != null+ ? 'Could not copy. Select the link below and copy it.'+ : _message(error),+ );+ }+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);- return AlertDialog(- title: Row(- children: [- const Icon(Icons.people_outline, size: 22),- const SizedBox(width: 12),- const Expanded(child: Text('Share harness')),- ],- ),- content: SizedBox(- width: 520,- child: ConstrainedBox(- constraints: BoxConstraints(- maxHeight: MediaQuery.sizeOf(context).height * .65,- ),- child: SingleChildScrollView(- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- mainAxisSize: MainAxisSize.min,- children: [- Text(- widget.name,- style: Theme.of(context).textTheme.titleMedium,- ),- const SizedBox(height: 6),- Text(- 'Let people watch your agent and its live output.',- style: TextStyle(color: grid.AppPalette.textSecondary),- ),- const SizedBox(height: 22),- const FieldLabel('Add people by email'),- TextField(- controller: _emails,- autofocus: true,- enabled: !_busy && !_loading,- keyboardType: TextInputType.emailAddress,- maxLines: 2,- minLines: 1,- decoration: const InputDecoration(- hintText: '[email protected], [email protected]',+ return ListenableBuilder(+ listenable: Listenable.merge([terminalFontStore, terminalThemeStore]),+ builder: (context, _) {+ final cell = terminalCellSizeOf(context);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ final style = terminalContentStyle(color: theme.foreground);+ final muted = style.copyWith(+ color: theme.foreground.withValues(alpha: .6),+ );+ final isPublic = _link?['visibility'] == 'public';+ final disabled = _busy || _loading;+ final gap = SizedBox(height: cell.height);+ Widget action(String label, VoidCallback? run) =>+ TerminalTextAction(label: label, onPressed: run);+ return TerminalPromptKeys(+ cancel: () => Navigator.of(context).pop(),+ child: Dialog(+ backgroundColor: theme.background,+ surfaceTintColor: Colors.transparent,+ elevation: 0,+ insetPadding: EdgeInsets.symmetric(+ horizontal: cell.width * 2,+ vertical: cell.height * 2,+ ),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),+ side: terminalPaneBorder(focused: true),+ ),+ child: DefaultTextStyle(+ style: style,+ child: SizedBox(+ width: cell.width * 68,+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: MediaQuery.sizeOf(context).height * .8,),- onSubmitted: (_) => _invite(),- onChanged: (_) => setState(() {}),- ),- const SizedBox(height: 12),- Row(- children: [- const Icon(Icons.visibility_outlined, size: 16),- const SizedBox(width: 8),- const Text('Can view'),- const Spacer(),- AppSelectField<int>(- value: _days,- width: 156,- options: const [- SelectOption(value: 7, label: 'Expires in 7 days'),- SelectOption(value: 30, label: 'Expires in 30 days'),- SelectOption(value: 90, label: 'Expires in 90 days'),- ],- onChanged: (value) {- if (!_busy) setState(() => _days = value);- },+ child: Padding(+ padding: EdgeInsets.symmetric(+ horizontal: cell.width * 2,+ vertical: cell.height,),- ],- ),- const SizedBox(height: 12),- FilledButton(- onPressed: _busy || _loading || _emails.text.trim().isEmpty- ? null- : _invite,- child: Text(_busy ? 'Saving…' : 'Share harness'),- ),- if (_error != null)- Padding(- padding: const EdgeInsets.only(top: 12),- child: Semantics(- liveRegion: true,- child: Text(- _error!,- style: TextStyle(- color: Theme.of(context).colorScheme.error,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ 'Share ${widget.name}',+ overflow: TextOverflow.ellipsis,+ style: style.copyWith(+ fontWeight: FontWeight.bold,+ ),+ ),+ ),+ if (_collaboration)+ action(+ _comments ? 'Access' : 'Comments',+ () => setState(() => _comments = !_comments),+ ),+ action('Done', () => Navigator.of(context).pop()),+ ],),- ),- ),- ),- if (_notice != null)- Padding(- padding: const EdgeInsets.only(top: 12),- child: Semantics(liveRegion: true, child: Text(_notice!)),- ),- const SizedBox(height: 24),- const Text(- 'People with access',- style: TextStyle(fontWeight: FontWeight.w600),- ),- const SizedBox(height: 10),- if (_loading)- const Padding(- padding: EdgeInsets.symmetric(vertical: 12),- child: Skeleton(height: 44),- ),- if (!_loading && _shares.isEmpty)- Padding(- padding: const EdgeInsets.symmetric(vertical: 10),- child: Text(- 'Only you have access.',- style: TextStyle(color: grid.AppPalette.textSecondary),+ gap,+ if (_comments)+ Flexible(+ child: SizedBox(+ height: cell.height * 25,+ child: HarnessComments(manage: widget.manage),+ ),+ )+ else+ Flexible(+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (_loading) const Text('Loading sharing…'),+ if (!_loading && !_collaboration)+ const Text(+ 'Update Harness on this machine to share browser links and comments.',+ ),+ if (_collaboration) ...[+ Wrap(+ children: [+ action(+ '${!isPublic ? 'x' : ' '} Private',+ disabled+ ? null+ : () => _linkAction('private'),+ ),+ action(+ '${isPublic ? 'x' : ' '} Public',+ disabled+ ? null+ : () => _linkAction('public'),+ ),+ ],+ ),+ Text(+ isPublic+ ? 'Anyone with the link can view live output and comments.'+ : 'Only the emails you add can view and comment.',+ style: muted,+ ),+ gap,+ Wrap(+ children: [+ action(+ _busy ? 'Saving…' : 'Copy link',+ disabled+ ? null+ : () => _linkAction(+ 'private',+ copy: true,+ ),+ ),+ if (_link != null &&+ _link?['visibility'] != 'off')+ action(+ 'Stop sharing',+ disabled+ ? null+ : () => _linkAction('off'),+ ),+ ],+ ),+ if (_manualCopy && _link?['url'] is String)+ Padding(+ padding: EdgeInsets.only(+ top: cell.height,+ ),+ child: SelectableText(+ _link!['url'] as String,+ style: muted,+ ),+ ),+ if (_link?['error'] != null)+ Text('${_link!['error']}'),+ gap,+ ],+ if (!isPublic) ...[+ const Text('Add people by email'),+ TextField(+ controller: _emails,+ autofocus: true,+ enabled: !disabled,+ keyboardType: TextInputType.emailAddress,+ maxLines: 2,+ minLines: 1,+ style: style,+ cursorColor: theme.cursor,+ decoration: InputDecoration(+ hintText: '[email protected], [email protected]',+ hintStyle: muted,+ filled: false,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ contentPadding: EdgeInsets.symmetric(+ vertical: cell.height / 2,+ ),+ ),+ onSubmitted: (_) => _invite(),+ onChanged: (_) => setState(() {}),+ ),+ Wrap(+ crossAxisAlignment:+ WrapCrossAlignment.center,+ children: [+ const Text('Expires in '),+ for (final days in [7, 30, 90])+ action(+ '${_days == days ? 'x ' : ''}$days days',+ disabled+ ? null+ : () => setState(+ () => _days = days,+ ),+ ),+ action(+ 'Add people',+ disabled ||+ _emails.text.trim().isEmpty+ ? null+ : _invite,+ ),+ ],+ ),+ ],+ if (_error != null)+ Padding(+ padding: EdgeInsets.only(+ top: cell.height,+ ),+ child: Semantics(+ liveRegion: true,+ child: Text(+ _error!,+ style: style.copyWith(+ color: theme.red,+ ),+ ),+ ),+ ),+ if (_notice != null)+ Padding(+ padding: EdgeInsets.only(+ top: cell.height,+ ),+ child: Semantics(+ liveRegion: true,+ child: Text(_notice!),+ ),+ ),+ gap,+ if (!_loading && !isPublic && _shares.isEmpty)+ Text(+ 'No invited people yet.',+ style: muted,+ ),+ for (final share+ in isPublic+ ? <Map<String, dynamic>>[]+ : _shares)+ Padding(+ padding: EdgeInsets.only(+ bottom: cell.height,+ ),+ child: Column(+ crossAxisAlignment:+ CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ '${share['email']}',+ overflow:+ TextOverflow.ellipsis,+ ),+ ),+ action(+ 'Remove',+ _busy+ ? null+ : () => _remove(+ share['id'] as String,+ ),+ ),+ ],+ ),+ Text(+ _recipientStatus(share),+ style: muted,+ ),+ ],+ ),+ ),+ Text(+ 'Keep your machine online while people watch. Viewers can comment; they cannot control your agent.',+ style: muted,+ ),+ if (_error != null && !_busy)+ Align(+ alignment: Alignment.centerLeft,+ child: action('Retry', () => _load()),+ ),+ ],+ ),+ ),+ ),+ ],),),- for (final share in _shares) _recipient(share),- const SizedBox(height: 18),- Container(- padding: const EdgeInsets.all(12),- decoration: BoxDecoration(- color: grid.AppSurface.recess,- borderRadius: BorderRadius.circular(8),- ),- child: Text(- 'They’ll find this harness in Machines → Shared with you using the invited email. '- 'Keep your machine online while they watch. You can remove access at any time.',- style: grid.AppType.body(height: 1.5),- ),),- ],+ ),),),- ),- ),- actions: [- if (_error != null && !_busy)- TextButton(onPressed: () => _load(), child: const Text('Retry')),- TextButton(- onPressed: () => Navigator.of(context).pop(),- child: const Text('Done'),- ),- ],+ );+ },);}- Widget _recipient(Map<String, dynamic> share) {- final email = share['email'] as String;- final watching = (share['watching'] as num? ?? 0) > 0;+ String _recipientStatus(Map<String, dynamic> share) {final expires = DateTime.tryParse(share['expiresAt'] as String? ?? '')?.toLocal();- final subtitle =- share['error'] as String? ??+ return share['error'] as String? ??(share['pending'] == true? 'Waiting for connection': share['expired'] == true? 'Expired · add again to renew'- : watching+ : (share['watching'] as num? ?? 0) > 0? 'Watching now · Can view': 'Can view${expires == null ? '' : ' · Until ${expires.month}/${expires.day}/${expires.year}'}');- return ListTile(- contentPadding: EdgeInsets.zero,- leading: CircleAvatar(- radius: 16,- backgroundColor: grid.AppSurface.recess,- child: Text(- email.substring(0, 1).toUpperCase(),- style: grid.AppType.label(),- ),- ),- title: Text(- email,- overflow: TextOverflow.ellipsis,- style: grid.AppType.label(),- ),- subtitle: Text(subtitle, style: grid.AppType.body()),- trailing: TextButton(- onPressed: _busy ? null : () => _remove(share['id'] as String),- child: const Text('Remove'),- ),- );}}diff --git a/desktop/lib/sharing/shared_agent_location.dart b/desktop/lib/sharing/shared_agent_location.dartnew file mode 100644index 000000000..e869805c2--- /dev/null+++ b/desktop/lib/sharing/shared_agent_location.dart@@ -0,0 +1,35 @@+/// Share URLs keep the pinned owner identity in the fragment, outside server/access logs.+class SharedAgentLocation {+ const SharedAgentLocation(this.id, this.ownerKey, this.environment);+ final String id;+ final String? ownerKey;+ final String environment;++ static SharedAgentLocation? parse(Uri uri) {+ final match = RegExp(+ r'^/s/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/?$',+ ).firstMatch(uri.path);+ if (match == null) return null;+ String? key;+ try {+ key = Uri.splitQueryString(uri.fragment)['key'];+ } on FormatException {+ /* An incomplete link has no trusted identity. */+ }+ final env = uri.queryParameters['env'] ?? 'prod';+ return SharedAgentLocation(match[1]!, key, env);+ }++ /// Only a local share path can be restored after OAuth. Never accept an external redirect.+ static String? returnPath(Object? value) {+ if (value is! String) return null;+ final uri = Uri.tryParse(value);+ if (uri == null ||+ uri.hasScheme ||+ uri.hasAuthority ||+ parse(uri) == null) {+ return null;+ }+ return uri.toString();+ }+}diff --git a/desktop/lib/sharing/shared_agent_page.dart b/desktop/lib/sharing/shared_agent_page.dartnew file mode 100644index 000000000..a8fb7dbd0--- /dev/null+++ b/desktop/lib/sharing/shared_agent_page.dart@@ -0,0 +1,242 @@+import 'dart:async';++import 'package:dio/dio.dart';+import 'package:flutter/material.dart';+import 'package:url_launcher/link.dart';++import '../core/models.dart';+import '../state/app_state.dart';+import '../state/terminal_pane.dart';+import '../terminal/terminal_text.dart';+import '../widgets/terminal_text_action.dart';+import '../widgets/web_download_button.dart';+import 'shared_agent_location.dart';+import 'shared_harness_panel.dart';++/// Public landing and private recipient view, using the same encrypted renderer as desktop.+/// It does not add a machine, receive a peer key, or restore the visitor's workspace.+class SharedAgentPage extends StatefulWidget {+ const SharedAgentPage({+ super.key,+ required this.app,+ required this.location,+ this.dio,+ });+ final AppNotifier app;+ final SharedAgentLocation location;+ final Dio? dio;+ @override+ State<SharedAgentPage> createState() => _SharedAgentPageState();+}++class _SharedAgentPageState extends State<SharedAgentPage> {+ late final _dio =+ widget.dio ??+ Dio(+ BaseOptions(+ connectTimeout: const Duration(seconds: 15),+ receiveTimeout: const Duration(seconds: 20),+ validateStatus: (_) => true,+ ),+ );+ Map<String, dynamic>? _data;+ String? _error;+ bool _loading = true, _signInRequired = false;+ int _revision = 0;+ Timer? _offlineRetry;+ late bool _signedIn = widget.app.status == AppStatus.authenticated;+ @override+ void initState() {+ super.initState();+ unawaited(_load());+ }++ @override+ void didUpdateWidget(SharedAgentPage oldWidget) {+ super.didUpdateWidget(oldWidget);+ final signedIn = widget.app.status == AppStatus.authenticated;+ if (signedIn != _signedIn || oldWidget.location.id != widget.location.id) {+ _signedIn = signedIn;+ unawaited(_load());+ }+ }++ @override+ void dispose() {+ _revision++;+ _offlineRetry?.cancel();+ if (widget.dio == null) _dio.close(force: true);+ super.dispose();+ }++ Future<void> _load() async {+ _offlineRetry?.cancel();+ final revision = ++_revision;+ setState(() {+ _loading = true;+ _data = null;+ _error = null;+ _signInRequired = false;+ });+ try {+ final key = widget.location.ownerKey;+ if (key == null || !RegExp(r'^[A-Za-z0-9+/]{43}=$').hasMatch(key)) {+ throw const FormatException(+ 'This link is incomplete. Ask the owner to copy the full link again.',+ );+ }+ final auth = widget.app.viewer?.auth;+ final token = auth != null && await auth.hasSession()+ ? await auth.accessToken()+ : null;+ final response = await _dio.get(+ '${widget.app.config.apiBaseUrl}/api/shared-agents/${widget.location.id}',+ options: Options(+ headers: {+ 'x-autonomous-env': widget.location.environment,+ if (token != null) 'Authorization': 'Bearer $token',+ },+ ),+ );+ if (!mounted || revision != _revision) return;+ if (response.statusCode != 200) {+ setState(() {+ _signInRequired = response.statusCode == 401;+ _error = _signInRequired+ ? 'This link is private. Sign in with an invited email.'+ : 'This link is unavailable or your email has not been invited. Ask the owner for access.';+ _loading = false;+ });+ return;+ }+ final data = Map<String, dynamic>.from(response.data['data'] as Map);+ if (data['ownerPublicKey'] != key) {+ throw const FormatException(+ 'The owner identity has changed. Ask the owner for a new link.',+ );+ }+ if (data['online'] != true) {+ setState(() {+ _loading = false;+ _error = 'The owner’s machine is offline. This page reconnects when it comes back.';+ });+ _offlineRetry = Timer(+ const Duration(seconds: 10),+ () => unawaited(_load()),+ );+ return;+ }+ setState(() {+ _data = data;+ _loading = false;+ });+ } catch (error) {+ if (mounted && revision == _revision) {+ setState(() {+ _loading = false;+ _error = error is FormatException ? error.message : 'Could not open this link. Check your connection and try again.';+ });+ }+ }+ }++ @override+ Widget build(BuildContext context) {+ final data = _data;+ return Scaffold(+ body: SafeArea(+ child: Column(+ children: [+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ child: Row(+ children: [+ Link(+ uri: Uri.parse('/'),+ builder: (context, follow) =>+ TerminalTextAction(label: 'Harness', onPressed: follow),+ ),+ const Spacer(),+ const WebDownloadButton(),+ ],+ ),+ ),+ Expanded(+ child: data != null+ ? SharedHarnessPanel(+ key: ValueKey('${widget.location.id}:$_signedIn'),+ notifier: widget.app,+ pane: TerminalPane(+ id: -1,+ machineId: data['machineId'] as String,+ agentId: data['agentId'] as String,+ ),+ grant: SharedHarness(+ id: widget.location.id,+ agentId: data['agentId'] as String,+ name: data['name'] as String,+ engine: data['engine'] as String?,+ expiresAt: DateTime.utc(9999),+ ownerPublicKey: widget.location.ownerKey,+ ),+ hasAccess: true,+ visible: true,+ link: true,+ linkEnvironment: widget.location.environment,+ onClose: () => setState(() {+ _data = null;+ _error = 'Viewing paused.';+ }),+ onSignIn: _signedIn+ ? null+ : () => unawaited(widget.app.login()),+ )+ : Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ _loading+ ? 'Opening shared agent…'+ : _error ?? 'Shared agent',+ style: terminalContentStyle(),+ textAlign: TextAlign.center,+ ),+ if (widget.app.lastError != null)+ Text(+ widget.app.lastError!,+ textAlign: TextAlign.center,+ ),+ const SizedBox(height: 20),+ if (_signInRequired)+ TerminalTextAction(+ label: widget.app.signingIn+ ? 'Signing in…'+ : 'Sign in',+ onPressed: widget.app.signingIn+ ? null+ : () => unawaited(widget.app.login()),+ ),+ if (!_loading && !_signInRequired)+ TerminalTextAction(+ label: 'Retry',+ onPressed: _load,+ ),+ if (!_loading && _signedIn && _data == null)+ TerminalTextAction(+ label: 'Switch account',+ onPressed: () => unawaited(widget.app.logout()),+ ),+ ],+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dartindex b28c50bf0..070145a60 100644--- a/desktop/lib/sharing/shared_harness_panel.dart+++ b/desktop/lib/sharing/shared_harness_panel.dart@@ -16,6 +16,8 @@ import '../terminal/terminal_session.dart';import '../widgets/terminal_panel.dart';import '../ws/ws_conn.dart';import '../viewer/observer_relay_codec.dart';+import '../widgets/terminal_text_action.dart';+import 'harness_comments.dart';class SharedHarnessPanel extends StatefulWidget {const SharedHarnessPanel({@@ -26,12 +28,18 @@ class SharedHarnessPanel extends StatefulWidget {required this.hasAccess,required this.visible,required this.onClose,+ this.link = false,+ this.linkEnvironment,+ this.onSignIn,});final AppNotifier notifier;final TerminalPane pane;final SharedHarness grant;final bool hasAccess, visible;final VoidCallback onClose;+ final bool link;+ final String? linkEnvironment;+ final VoidCallback? onSignIn;@overrideState<SharedHarnessPanel> createState() => _SharedHarnessPanelState();}@@ -53,6 +61,8 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {bool _viewerChosen = false;String _lastViewerState = '';int _generation = 0;+ bool _commentsSelected = false, _commentsOpened = false;+ final _commentUpdates = ValueNotifier<int>(0);@overridevoid initState() {super.initState();@@ -77,9 +87,11 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {);_connection = WsConn(wsBaseUrl: widget.notifier.config.wsBaseUrl,- autonomousEnv: widget.notifier.config.autonomousEnv,+ autonomousEnv:+ widget.linkEnvironment ?? widget.notifier.config.autonomousEnv,machineId: widget.pane.machineId,observerShareId: widget.grant.id,+ observerLink: widget.link,transportKind: viewer == null? WsTransportKind.localPlaintext: WsTransportKind.cloudE2ee,@@ -88,6 +100,8 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {? widget.notifier.localDaemonTransport: null,accessTokenProvider: (force, failedToken) async => viewer == null+ ? ''+ : widget.link && !await viewer.auth.hasSession()? '': viewer.auth.accessToken(force: force, failedToken: failedToken),relayCodecs: viewer == null@@ -153,6 +167,8 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {? 'Live viewer': 'Opening the viewer…');});+ } else if (type == 'observer_comments') {+ _commentUpdates.value++;} else {await _terminal.handleFrame(type, payload);}@@ -222,9 +238,19 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {void dispose() {unawaited(_connection.close());_terminal.dispose();+ _commentUpdates.dispose();super.dispose();}+ void _retry() {+ unawaited(_connection.close());+ _terminal.dispose();+ _ended = false;+ _failure = null;+ _status = ConnectionStatus.connecting;+ setState(_start);+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -233,50 +259,54 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {return Column(children: [Container(- height: 44,- padding: const EdgeInsets.only(left: 12, right: 4),+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),color: grid.AppSurface.recess,- child: Row(+ child: Column(children: [- const Icon(Icons.visibility_outlined, size: 16),- const SizedBox(width: 8),- Expanded(- child: Text(- widget.grant.name,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- fontWeight: grid.AppFont.semibold,+ Row(+ children: [+ Expanded(+ child: Text(+ widget.grant.name,+ overflow: TextOverflow.ellipsis,+ style: terminalContentStyle().copyWith(+ fontWeight: FontWeight.bold,+ ),+ ),),- ),- ),- const SizedBox(width: 8),- Text(- 'View only',- style: grid.AppType.monoLabel(fontWeight: grid.AppFont.regular),- ),- const SizedBox(width: 12),- Tooltip(- message:- _failure ??- (live- ? 'Watching ${widget.pane.sharedOwnerName ?? 'the owner'}’s harness'- : 'Waiting for the owner’s machine. Reconnecting automatically.'),- child: Text(- _ended- ? 'Sharing ended'- : live- ? 'Live'- : 'Reconnecting',- style: grid.AppType.monoLabel(- fontWeight: grid.AppFont.regular,- color: grid.AppPalette.textSecondary,+ const SizedBox(width: 8),+ Text('View only', style: terminalContentStyle()),+ IconButton(+ tooltip: 'Close shared harness',+ onPressed: widget.onClose,+ icon: const Icon(Icons.close, size: 16),),- ),+ ],),- IconButton(- tooltip: 'Close shared harness',- onPressed: widget.onClose,- icon: const Icon(Icons.close, size: 16),+ Row(+ children: [+ Expanded(+ child: Text(+ _ended+ ? 'Sharing ended'+ : live+ ? 'Live'+ : 'Reconnecting',+ style: terminalContentStyle(+ color: grid.AppPalette.textSecondary,+ ),+ ),+ ),+ if (_ended && widget.hasAccess)+ TerminalTextAction(label: 'Retry', onPressed: _retry),+ TerminalTextAction(+ label: _commentsSelected ? 'Watch' : 'Comments',+ onPressed: () => setState(() {+ _commentsSelected = !_commentsSelected;+ _commentsOpened = true;+ }),+ ),+ ],),],),@@ -290,109 +320,170 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {),Expanded(child: LayoutBuilder(- builder: (context, constraints) {- Widget terminal() => TerminalPanel(- notifier: widget.notifier,- session: _terminal,- focused: widget.notifier.isPaneFocused(widget.pane.id),- visible: widget.visible,- showHeader: false,- readOnly: true,- viewportSize: constraints.biggest,- );- Widget viewer() => ColoredBox(- color: grid.AppPalette.windowBg,- child: Center(- child: _image == null- ? Padding(- padding: const EdgeInsets.all(24),- child: Column(- mainAxisSize: MainAxisSize.min,+ builder: (context, size) {+ final wide = size.maxWidth >= 1000;+ final commentsWidth = wide+ ? (terminalCellSizeOf(context).width * 44).clamp(+ 280.0,+ size.maxWidth * .45,+ )+ : size.maxWidth;+ return Stack(+ children: [+ Positioned.fill(+ right: _commentsSelected && wide ? commentsWidth : 0,+ child: Offstage(+ offstage: _commentsSelected && !wide,+ child: LayoutBuilder(+ builder: (context, constraints) {+ Widget terminal() => TerminalPanel(+ notifier: widget.notifier,+ session: _terminal,+ focused: widget.notifier.isPaneFocused(+ widget.pane.id,+ ),+ visible: widget.visible,+ showHeader: false,+ readOnly: true,+ viewportSize: constraints.biggest,+ );+ Widget viewer() => ColoredBox(+ color: grid.AppPalette.windowBg,+ child: Center(+ child: _image == null+ ? Padding(+ padding: const EdgeInsets.all(24),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (!_ended)+ const Skeleton(+ width: 220,+ height: 130,+ ),+ const SizedBox(height: 14),+ Text(+ _viewerMessage,+ textAlign: TextAlign.center,+ style: grid.AppType.body(+ color:+ grid.AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ )+ : Image.memory(+ _image!,+ gaplessPlayback: true,+ fit: BoxFit.contain,+ semanticLabel:+ 'Live output from ${widget.grant.name}',+ errorBuilder: (_, _, _) => const Text(+ 'Waiting for the next viewer frame.',+ ),+ ),+ ),+ );+ if (constraints.maxWidth >= 880) {+ return Row(+ children: [+ Expanded(flex: 5, child: terminal()),+ VerticalDivider(+ width: 1,+ color: grid.AppPalette.textFaint,+ ),+ Expanded(flex: 4, child: viewer()),+ ],+ );+ }+ return Column(children: [- if (!_ended)- const Skeleton(width: 220, height: 130),- const SizedBox(height: 14),- Text(- _viewerMessage,- textAlign: TextAlign.center,- style: grid.AppType.body(- color: grid.AppPalette.textSecondary,+ Row(+ children: [+ TextButton(+ onPressed: () => setState(() {+ _viewerChosen = true;+ _viewerSelected = false;+ }),+ child: Text(+ 'Terminal',+ style: TextStyle(+ fontWeight: !_viewerSelected+ ? FontWeight.w600+ : FontWeight.normal,+ ),+ ),+ ),+ TextButton(+ onPressed: () => setState(() {+ _viewerChosen = true;+ _viewerSelected = true;+ }),+ child: Text(+ 'Viewer',+ style: TextStyle(+ fontWeight: _viewerSelected+ ? FontWeight.w600+ : FontWeight.normal,+ ),+ ),+ ),+ const Spacer(),+ Flexible(+ child: Text(+ widget.pane.sharedOwnerName ??+ 'Shared harness',+ overflow: TextOverflow.ellipsis,+ style: grid.AppType.monoLabel(+ fontWeight: grid.AppFont.regular,+ ),+ ),+ ),+ const SizedBox(width: 12),+ ],+ ),+ Expanded(+ child: IndexedStack(+ index: _viewerSelected ? 1 : 0,+ children: [terminal(), viewer()],),),],- ),- )- : Image.memory(- _image!,- gaplessPlayback: true,- fit: BoxFit.contain,- semanticLabel:- 'Live output from ${widget.grant.name}',- errorBuilder: (_, _, _) =>- const Text('Waiting for the next viewer frame.'),- ),- ),- );- if (constraints.maxWidth >= 880) {- return Row(- children: [- Expanded(flex: 5, child: terminal()),- VerticalDivider(width: 1, color: grid.AppPalette.textFaint),- Expanded(flex: 4, child: viewer()),- ],- );- }- return Column(- children: [- Row(- children: [- TextButton(- onPressed: () => setState(() {- _viewerChosen = true;- _viewerSelected = false;- }),- child: Text(- 'Terminal',- style: TextStyle(- fontWeight: !_viewerSelected- ? FontWeight.w600- : FontWeight.normal,- ),- ),+ );+ },),- TextButton(- onPressed: () => setState(() {- _viewerChosen = true;- _viewerSelected = true;- }),- child: Text(- 'Viewer',- style: TextStyle(- fontWeight: _viewerSelected- ? FontWeight.w600- : FontWeight.normal,+ ),+ ),+ if (_commentsOpened)+ Positioned(+ top: 0,+ bottom: 0,+ right: 0,+ width: commentsWidth,+ child: Offstage(+ offstage: !_commentsSelected,+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: grid.AppPalette.windowBg,+ border: Border(+ left: BorderSide(color: grid.AppPalette.divider),+ ),),- ),- ),- const Spacer(),- Flexible(- child: Text(- widget.pane.sharedOwnerName ?? 'Shared harness',- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- fontWeight: grid.AppFont.regular,+ child: HarnessComments(+ updates: _commentUpdates,+ onSignIn: widget.onSignIn,+ manage: (action, payload) => _connection.request(+ 'observer_$action',+ payload: {+ 'agentId': widget.grant.agentId,+ ...payload,+ },+ ),),),),- const SizedBox(width: 12),- ],- ),- Expanded(- child: IndexedStack(- index: _viewerSelected ? 1 : 0,- children: [terminal(), viewer()],),- ),],);},diff --git a/desktop/lib/viewer/browser_login.dart b/desktop/lib/viewer/browser_login.dartindex 89b476c2e..cf931801e 100644--- a/desktop/lib/viewer/browser_login.dart+++ b/desktop/lib/viewer/browser_login.dart@@ -5,6 +5,7 @@ import '../auth/cli_login.dart' show CliAuthStatus;import '../auth/sign_in_client.dart';import 'direct_auth.dart';import 'direct_auth_api.dart';+import '../sharing/shared_agent_location.dart';/// Browser-only operations behind a seam so OAuth can be tested without a/// browser, a real account, or opening an authorization page.@@ -70,6 +71,8 @@ class BrowserLogin implements SignInClient {'This sign-in expired or started in another tab. Sign in again.',);}+ final returnTo = SharedAgentLocation.returnPath(saved['returnTo']);+ if (returnTo != null) browser.replaceLocation(returnTo);if (uri.queryParameters.containsKey('error')) {throw const DirectAuthException('Sign-in was not completed. Try again.',@@ -135,6 +138,12 @@ class BrowserLogin implements SignInClient {'tx': start.tx,'state': state,'createdAt': _clock().millisecondsSinceEpoch,+ if (SharedAgentLocation.parse(location) != null)+ 'returnTo': Uri(+ path: location.path,+ query: location.hasQuery ? location.query : null,+ fragment: location.hasFragment ? location.fragment : null,+ ).toString(),});final departing = _departing = Completer<void>();onAuthorizeUrl(start.authorizeUrl);diff --git a/desktop/lib/viewer/observer_relay_codec.dart b/desktop/lib/viewer/observer_relay_codec.dartindex 5b6619872..28314787c 100644--- a/desktop/lib/viewer/observer_relay_codec.dart+++ b/desktop/lib/viewer/observer_relay_codec.dart@@ -66,6 +66,9 @@ class ObserverRelayCodec implements RelayCodec {'terminal_resync','terminal_close','observer_viewer',+ 'observer_comments',+ 'observer_comment_post',+ 'observer_comment_remove',};@overridediff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex b65479862..9e920f203 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -88,6 +88,7 @@ class WsConn {/// Retained only for fixture constructor compatibility. Local transport ignores it.final String? localApiKey;final String? observerShareId;+ final bool observerLink;bool get _directObserver => !isLocal && observerShareId != null;final int localProtocolVersion;@@ -194,6 +195,7 @@ class WsConn {this.localTransport,this.localApiKey,this.observerShareId,+ this.observerLink = false,this.localProtocolVersion = 1,this.fixedReconnectDelay,this.relayCodecs,@@ -246,7 +248,9 @@ class WsConn {);try {final token = isLocal ? null : await accessTokenProvider(false, null);- if (!isLocal && (token == null || token.isEmpty)) {+ if (!isLocal &&+ !(_directObserver && observerLink) &&+ (token == null || token.isEmpty)) {throw StateError('WebSocket credential is missing');}if (_closing) return;@@ -289,13 +293,17 @@ class WsConn {queryParameters: {...base.queryParameters,'autonomousEnv': autonomousEnv,- if (_directObserver) 'share': observerShareId!,+ if (_directObserver)+ (observerLink ? 'link' : 'share'): observerShareId!,},);}final socket = isLocal ? _localSocket() : null;final channel = !isLocal- ? WebSocketChannel.connect(uri, protocols: [token!])+ ? WebSocketChannel.connect(+ uri,+ protocols: token == null || token.isEmpty ? null : [token],+ ): socket != null? await _connectLocalSocket(uri, socket) ??WebSocketChannel.connect(uri)@@ -582,7 +590,10 @@ class WsConn {'pong',};- static bool _worthLogging(String type) => !_unlogged.contains(type);+ static bool _worthLogging(String type) =>+ !_unlogged.contains(type) &&+ !type.startsWith('harness_share_') &&+ !type.startsWith('observer_');Future<Map<String, dynamic>> request(String type, {diff --git a/desktop/pubspec.lock b/desktop/pubspec.lockindex 01ce3a39b..336f63073 100644--- a/desktop/pubspec.lock+++ b/desktop/pubspec.lock@@ -273,7 +273,7 @@ packages:source: sdkversion: "0.0.0"flutter_web_plugins:- dependency: transitive+ dependency: "direct main"description: fluttersource: sdkversion: "0.0.0"diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex 926e81969..08c52b0b0 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -32,6 +32,8 @@ dependencies:archive: ^4.0.9flutter:sdk: flutter+ flutter_web_plugins:+ sdk: flutter# Natural ordering for numbered agents, projects, and completion candidates.collection: ^1.19.1diff --git a/desktop/scripts/check-sharing.cjs b/desktop/scripts/check-sharing.cjsnew file mode 100644index 000000000..bf600b61f--- /dev/null+++ b/desktop/scripts/check-sharing.cjs@@ -0,0 +1,97 @@+// Invoked by cli/scripts/share-harness-e2e.ts against disposable accounts and services only.+const { chromium } = require(process.env.HARNESS_PLAYWRIGHT_MODULE || 'playwright');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const fixture = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));+const { origin, backendUrl, mode, token, root } = fixture;+assert.equal(new URL(origin).hostname, '127.0.0.1');+assert.equal(new URL(backendUrl).hostname, '127.0.0.1');+const link = new URL(fixture.url);+const address = origin + link.pathname + link.search + link.hash;++(async () => {+ const browser = await chromium.launch({ channel: 'chrome', headless: true });+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });+ const errors = [];+ const page = await context.newPage();+ page.on('pageerror', error => errors.push(error.message));+ async function semantics() {+ await page.locator('flutter-view').waitFor({ state: 'attached', timeout: 45000 });+ const placeholder = page.locator('flt-semantics-placeholder');+ if (await placeholder.count()) await placeholder.evaluate(el => el.click());+ }+ const cors = { 'access-control-allow-origin': origin, 'access-control-allow-headers': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS' };+ try {+ await context.route('**/*', async route => {+ const url = new URL(route.request().url());+ // Every application call below is real except the SSO redirect/code exchange. No real account+ // credentials or external analytics services may participate in this fixture.+ if (![origin, backendUrl].includes(url.origin)) return route.abort();+ if (url.pathname === '/api/auth/authorize-native') {+ return route.fulfill({ headers: cors, contentType: 'application/json', body: JSON.stringify({ success: true, data: {+ authorizeUrl: `${origin}/fixture-authorize?state=share-fixture&redirect_uri=${encodeURIComponent(origin + '/callback')}`, tx: 'share-transaction',+ } }) });+ }+ if (url.pathname === '/fixture-authorize') {+ return route.fulfill({ status: 302, headers: { location: origin + '/callback?code=share-code&state=share-fixture' }, body: '' });+ }+ if (url.pathname === '/api/auth/exchange') {+ const input = route.request().postDataJSON();+ assert.equal(input.code, 'share-code'); assert.equal(input.state, 'share-fixture'); assert.equal(input.tx, 'share-transaction');+ return route.fulfill({ headers: cors, contentType: 'application/json', body: JSON.stringify({ success: true, data: {+ token, refreshToken: 'fixture-refresh', expiresIn: 3600, autonomousEnv: 'prod',+ } }) });+ }+ return route.continue();+ });+ await page.goto(address); await semantics();+ if (mode !== 'public') {+ await page.getByText('This link is private. Sign in with an invited email.', { exact: true }).waitFor();+ await page.getByRole('button', { name: 'Sign in', exact: true }).click();+ await page.waitForURL('**/callback?**'); await semantics();+ await page.waitForURL(url => url.pathname === link.pathname && url.hash === link.hash, { timeout: 30000 });+ assert.ok(!page.url().includes('share-code'));+ }+ if (mode === 'denied') {+ await page.getByText('This link is unavailable or your email has not been invited. Ask the owner for access.', { exact: true }).waitFor({ timeout: 30000 });+ assert.equal(await page.getByText('View only', { exact: true }).count(), 0);+ } else {+ await page.getByText('View only', { exact: true }).waitFor({ timeout: 30000 });+ await page.getByText('Live', { exact: true }).waitFor({ timeout: 30000 });+ await page.screenshot({ path: path.join(root, `share-${mode}-desktop.png`) });+ await page.getByRole('button', { name: 'Comments', exact: true }).click();+ await page.getByText('Comments (1)', { exact: true }).waitFor({ timeout: 30000 });+ fs.writeFileSync(path.join(root, `browser-${mode}-dom.html`), await page.content());+ const accessible = await page.locator('body').ariaSnapshot();+ fs.writeFileSync(path.join(root, `browser-${mode}-aria.txt`), accessible);+ assert.match(accessible, /Fixture collaboration/);+ if (mode === 'public') {+ await page.getByRole('button', { name: 'Sign in to comment', exact: true }).waitFor();+ assert.equal(await page.locator('textarea:not([readonly]):not([disabled]), input:not([readonly]):not([disabled])').count(), 0);+ } else {+ const text = 'Browser collaborator — private link';+ await page.getByRole('textbox').last().fill(text);+ await page.getByRole('button', { name: 'Comment', exact: true }).click();+ await page.getByText('Comments (2)', { exact: true }).waitFor();+ assert.ok((await page.locator('body').ariaSnapshot()).includes(text));+ assert.equal(await page.getByRole('textbox').last().inputValue(), '');+ }+ await page.setViewportSize({ width: 390, height: 844 });+ await page.screenshot({ path: path.join(root, `share-${mode}-phone.png`) });+ const download = await page.getByRole('link', { name: 'Download app', exact: true }).boundingBox();+ assert.ok(download && download.x >= 0 && download.x + download.width <= 390);+ assert.equal(new URL(page.url()).hash, link.hash);+ await page.reload(); await semantics();+ await page.getByText('Live', { exact: true }).waitFor({ timeout: 30000 });+ assert.equal(new URL(page.url()).hash, link.hash);+ }+ assert.deepEqual(errors, []);+ console.log(`PASS browser ${mode}: real encrypted sharing, access policy, comments, and responsive view`);+ } catch (error) {+ fs.writeFileSync(path.join(root, `browser-${mode}-failure.html`), await page.content());+ fs.writeFileSync(path.join(root, `browser-${mode}-failure.txt`), `${error.stack}\n${(await page.locator('body').innerText()).slice(0, 10000)}\n${errors.join('\n')}`);+ await page.screenshot({ path: path.join(root, `browser-${mode}-failure.png`) });+ throw error;+ } finally { await browser.close(); }+})().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/desktop/scripts/serve-web.py b/desktop/scripts/serve-web.pyindex fc4bfeb01..3f61462ec 100644--- a/desktop/scripts/serve-web.py+++ b/desktop/scripts/serve-web.py@@ -10,7 +10,8 @@ from urllib.parse import urlsplitclass WebPreview(SimpleHTTPRequestHandler):def do_GET(self):- if urlsplit(self.path).path in {"/callback", "/auth/callback"}:+ path = urlsplit(self.path).path+ if path in {"/callback", "/auth/callback"} or path.startswith("/s/"):self.path = "/index.html"super().do_GET()diff --git a/desktop/test/browser_login_test.dart b/desktop/test/browser_login_test.dartindex 3229fba53..5dff63016 100644--- a/desktop/test/browser_login_test.dart+++ b/desktop/test/browser_login_test.dart@@ -8,6 +8,7 @@ import 'package:harness/core/local_key_value_store.dart';import 'package:harness/viewer/browser_login.dart';import 'package:harness/viewer/direct_auth.dart';import 'package:harness/viewer/direct_auth_api.dart';+import 'package:harness/sharing/shared_agent_location.dart';class _Storage implements LocalKeyValueStore {final values = <String, String>{};@@ -92,6 +93,49 @@ void main() {);});+ test('sign-in returns to a pinned share link and never accepts an external return path', () async {+ final share =+ '/s/11111111-1111-4111-8111-111111111111#key=${Uri.encodeComponent(base64Encode(List.filled(32, 1)))}';+ browser.uri = Uri.parse('https://harness.example$share');+ final pending = login.login(onAuthorizeUrl: (_) {});+ final cancelled = expectLater(pending, throwsA(isA<DirectAuthException>()));+ api.authorization.complete((+ authorizeUrl: Uri.https('sso.example', '/authorize', {+ 'state': 'expected',+ 'redirect_uri': 'https://harness.example/auth/callback',+ }).toString(),+ tx: 'transaction',+ ));+ await Future<void>.delayed(Duration.zero);+ final saved = browser.transaction!;+ expect(jsonDecode(saved)['returnTo'], share);+ login.cancel();+ await cancelled;+ browser.transaction = saved;+ browser.uri = Uri.parse(+ 'https://harness.example/auth/callback?state=expected&code=one-use',+ );+ final status = login.checkStatus();+ await Future<void>.delayed(Duration.zero);+ expect(browser.uri.toString(), 'https://harness.example$share');+ api.exchanged.complete(+ const IssuedTokens(+ token: 'access',+ refreshToken: 'refresh',+ expiresIn: 3600,+ ),+ );+ expect((await status).loggedIn, isTrue);+ for (final invalid in [+ 'https://evil.example$share',+ '//evil.example$share',+ '/auth/callback?code=secret',+ '/s/invalid',+ ]) {+ expect(SharedAgentLocation.returnPath(invalid), isNull);+ }+ });+test('authorization stays in this tab and cancellation discards its transaction',() async {diff --git a/desktop/test/harness_comments_test.dart b/desktop/test/harness_comments_test.dartnew file mode 100644index 000000000..0ef1f9d5d--- /dev/null+++ b/desktop/test/harness_comments_test.dart@@ -0,0 +1,102 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/sharing/harness_comments.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;++void main() {+ Future<void> show(+ WidgetTester tester,+ CommentAction manage, {+ VoidCallback? signIn,+ }) => tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: HarnessComments(manage: manage, onSignIn: signIn),+ ),+ ),+ );++ testWidgets('public guests can read and sign in but cannot post', (+ tester,+ ) async {+ var signIns = 0;+ await show(+ tester,+ (_, _) async => {+ 'canComment': false,+ 'comments': [+ {+ 'id': 'one',+ 'authorName': 'Alice',+ 'text': 'Looks good 👋',+ 'canDelete': false,+ },+ ],+ },+ signIn: () => signIns++,+ );+ await tester.pump();+ expect(find.text('Looks good 👋'), findsOneWidget);+ expect(find.byType(TextField), findsNothing);+ expect(find.text('[ Remove ]'), findsNothing);+ await tester.tap(find.text('[ Sign in to comment ]'));+ expect(signIns, 1);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets(+ 'failed posting retains the draft and id; retry, broadcast refresh and removal work',+ (tester) async {+ final requests = <Map<String, dynamic>>[];+ var comments = <Map<String, dynamic>>[];+ var fail = true;+ await show(tester, (action, payload) async {+ if (action == 'comment_post') {+ requests.add(payload);+ if (fail) {+ fail = false;+ throw StateError('offline');+ }+ comments = [+ {+ 'id': payload['id'],+ 'authorName': 'Alice',+ 'text': payload['text'],+ 'canDelete': true,+ },+ ];+ }+ if (action == 'comment_remove') comments = [];+ return {'canComment': true, 'comments': comments};+ });+ await tester.pump();+ await tester.enterText(+ find.byKey(const Key('comment-input')),+ 'Hello team',+ );+ await tester.pump();+ await tester.tap(find.text('[ Comment ]'));+ await tester.pump();+ expect(find.textContaining('Your draft is saved'), findsOneWidget);+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ 'Hello team',+ );+ await tester.tap(find.text('[ Comment ]'));+ await tester.pump();+ expect(requests, hasLength(2));+ expect(requests[0]['id'], requests[1]['id']);+ expect(find.text('Hello team'), findsOneWidget);+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ isEmpty,+ );+ await tester.tap(find.text('[ Remove ]'));+ await tester.pump();+ expect(find.text('Hello team'), findsNothing);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ );+}diff --git a/desktop/test/share_harness_test.dart b/desktop/test/share_harness_test.dartindex 3f9f9ed6d..f10fad8e7 100644--- a/desktop/test/share_harness_test.dart+++ b/desktop/test/share_harness_test.dart@@ -97,7 +97,114 @@ void main() {'expired': expired,'watching': watching,};- final submit = find.widgetWithText(FilledButton, 'Share harness');+ final submit = find.widgetWithText(TextButton, '[ Add people ]');++ Future<void> capture(WidgetTester tester, String state) async {+ final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];+ if (output == null) return;+ await tester.pump(const Duration(milliseconds: 300));+ final boundary = tester.renderObject<RenderRepaintBoundary>(+ find.byKey(const Key('sharing-dialog-preview')),+ );+ await tester.runAsync(() async {+ final image = await boundary.toImage();+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$output.$state.png').writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ }++ testWidgets(+ 'one stable browser link can be copied, made public/private and stopped',+ (tester) async {+ Map<String, dynamic>? link;+ final changes = <String>[];+ String? clipboard;+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ SystemChannels.platform,+ (call) async {+ if (call.method == 'Clipboard.setData') {+ clipboard = (call.arguments as Map)['text'] as String;+ }+ return null;+ },+ );+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ SystemChannels.platform,+ null,+ ),+ );+ await show(tester, (action, payload) async {+ if (action == 'link') {+ changes.add(payload['visibility'] as String);+ link = {+ 'visibility': payload['visibility'],+ 'pending': false,+ 'error': null,+ 'url': 'https://harness.example/s/fixture#key=pinned',+ };+ }+ return {'collaboration': true, 'link': link, 'shares': []};+ });+ expect(+ find.text('Only the emails you add can view and comment.'),+ findsOneWidget,+ );+ await tester.tap(find.text('[ Copy link ]'));+ await tester.pump();+ expect(changes, ['private']);+ expect(clipboard, 'https://harness.example/s/fixture#key=pinned');+ expect(find.text('Link copied.'), findsOneWidget);+ await capture(tester, 'private');+ await tester.tap(find.textContaining('Public').first);+ await tester.pump();+ expect(changes.last, 'public');+ expect(find.textContaining('Anyone with the link'), findsOneWidget);+ await capture(tester, 'public');+ await tester.tap(find.text('[ Copy link ]'));+ await tester.pump();+ expect(changes, [+ 'private',+ 'public',+ ], reason: 'copying never silently changes visibility');+ await tester.tap(find.textContaining('Private').first);+ await tester.pump();+ expect(changes.last, 'private');+ await tester.tap(find.text('[ Stop sharing ]'));+ await tester.pump();+ expect(changes.last, 'off');+ expect(find.text('Sharing stopped.'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'a pending link is not copied and an older daemon keeps actionable update guidance',+ (tester) async {+ await show(+ tester,+ (action, _) async => {+ 'collaboration': true,+ 'shares': [],+ 'link': action == 'list'+ ? null+ : {+ 'visibility': 'private',+ 'pending': true,+ 'error': null,+ 'url': 'https://harness.example/s/pending#key=pin',+ },+ },+ );+ await tester.tap(find.text('[ Copy link ]'));+ await tester.pump();+ expect(find.textContaining('Waiting for the connection'), findsOneWidget);+ expect(find.text('Link copied.'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ },+ );testWidgets('agent-pane entry point manages the exact selected harness', (tester,@@ -125,8 +232,8 @@ void main() {await tester.tap(find.text('Share'));await tester.pumpAndSettle();expect(app.calls, [('machine', 'agent', 'list')]);- expect(find.text('Climate dashboard'), findsOneWidget);- await tester.tap(find.text('Done'));+ expect(find.text('Share Climate dashboard'), findsOneWidget);+ await tester.tap(find.text('[ Done ]'));await tester.pumpAndSettle();app.dispose();});@@ -153,9 +260,7 @@ void main() {'shares': [person('[email protected]')],};});- await tester.tap(find.text('Expires in 30 days'));- await tester.pumpAndSettle();- await tester.tap(find.text('Expires in 7 days').last);+ await tester.tap(find.text('[ 7 days ]'));await tester.pumpAndSettle();await tester.enterText(find.byType(TextField), '[email protected]');tester@@ -165,7 +270,7 @@ void main() {await tester.pump();expect(invites.single['days'], 7);expect(find.text('This harness cannot be shared yet.'), findsOneWidget);- await tester.tap(find.widgetWithText(TextButton, 'Remove'));+ await tester.tap(find.widgetWithText(TextButton, '[ Remove ]'));await tester.pump();expect(removing, isTrue);expect(find.textContaining('Check the connection'), findsOneWidget);@@ -192,8 +297,8 @@ void main() {}return {'shares': shares};});- expect(find.text('Only you have access.'), findsOneWidget);- expect(find.text('Can view'), findsOneWidget);+ expect(find.text('No invited people yet.'), findsOneWidget);+ expect(find.textContaining('cannot control your agent'), findsOneWidget);await tester.enterText(find.byType(TextField),@@ -208,7 +313,7 @@ void main() {});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(find.textContaining('Keep your machine online'), findsOneWidget);expect(tester.takeException(), isNull);// Optional artifact for visual review; no golden files or production filesystem writes.final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];@@ -224,7 +329,7 @@ void main() {image.dispose();});}- await tester.tap(find.widgetWithText(TextButton, 'Remove').first);+ await tester.tap(find.widgetWithText(TextButton, '[ Remove ]').first);await tester.pump();expect(calls.last.$1, 'remove');expect(calls.last.$2, {'id': '[email protected]'});@@ -232,7 +337,7 @@ void main() {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.tap(find.text('[ Done ]'));await tester.pumpAndSettle();expect(find.text('Share harness'), findsNothing);},@@ -250,10 +355,7 @@ void main() {}return {'shares': []};});- expect(- tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,- isNull,- );+ expect(tester.widget<TextButton>(submit).onPressed, isNull);for (final invalid in ['bad',List.generate(21, (i) => '[email protected]').join(','),@@ -269,11 +371,8 @@ void main() {await tester.pump();await tester.tap(submit);await tester.pump();- expect(find.text('Saving…'), findsOneWidget);- expect(- tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,- isNull,- );+ expect(tester.widget<TextField>(find.byType(TextField)).enabled, isFalse);+ expect(tester.widget<TextButton>(submit).onPressed, isNull);await tester.pump(const Duration(seconds: 5));expect(invites, 1);pending.complete({@@ -327,14 +426,14 @@ void main() {findsOneWidget,);fails = false;- await tester.tap(find.text('Retry'));+ await tester.tap(find.text('[ Retry ]'));await tester.pump();- expect(find.text('Only you have access.'), findsOneWidget);- expect(find.text('Retry'), findsNothing);+ expect(find.text('No invited people yet.'), 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.tap(find.text('[ Done ]'));await tester.pumpAndSettle();pending.complete({'shares': []});await tester.pump();diff --git a/desktop/test/shared_agent_page_test.dart b/desktop/test/shared_agent_page_test.dartnew file mode 100644index 000000000..a38791108--- /dev/null+++ b/desktop/test/shared_agent_page_test.dart@@ -0,0 +1,141 @@+import 'dart:convert';++import 'package:dio/dio.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/sharing/shared_agent_location.dart';+import 'package:harness/sharing/shared_agent_page.dart';+import 'package:harness/sharing/shared_harness_panel.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';++import 'support/real_fonts.dart';++void main() {+ setUpAll(loadRealFonts);+ const id = '11111111-1111-4111-8111-111111111111';+ final key = base64Encode(List.filled(32, 1));+ late AppNotifier app;+ late Dio dio;+ late List<RequestOptions> requests;+ late int status;+ late Map<String, dynamic> metadata;++ setUp(() {+ app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ requests = [];+ status = 200;+ metadata = {'ownerPublicKey': key, 'online': false};+ dio = Dio()+ ..interceptors.add(+ InterceptorsWrapper(+ onRequest: (request, handler) {+ requests.add(request);+ handler.resolve(+ Response(+ requestOptions: request,+ statusCode: status,+ data: {'data': metadata},+ ),+ );+ },+ ),+ );+ });+ tearDown(() {+ dio.close();+ app.dispose();+ });++ Future<void> show(WidgetTester tester, {String? pinnedKey}) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SharedAgentPage(+ app: app,+ dio: dio,+ location: SharedAgentLocation(id, pinnedKey, 'stag'),+ ),+ ),+ );+ for (+ var i = 0;+ i < 20 && find.text('Opening shared agent…').evaluate().isNotEmpty;+ i+++ ) {+ await tester.pump(const Duration(milliseconds: 10));+ }+ }++ testWidgets('incomplete and changed owner identities never open a viewer', (+ tester,+ ) async {+ await show(tester);+ expect(find.textContaining('This link is incomplete'), findsOneWidget);+ expect(requests, isEmpty);+ expect(find.byType(SharedHarnessPanel), findsNothing);+ await tester.pumpWidget(const SizedBox());+ metadata['ownerPublicKey'] = base64Encode(List.filled(32, 2));+ await show(tester, pinnedKey: key);+ expect(+ find.textContaining('The owner identity has changed'),+ findsOneWidget,+ );+ expect(find.byType(SharedHarnessPanel), findsNothing);+ expect(requests.single.headers['x-autonomous-env'], 'stag');+ expect(requests.single.headers.containsKey('Authorization'), isFalse);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets(+ 'private and denied links show access guidance without opening a viewer',+ (tester) async {+ status = 401;+ await show(tester, pinnedKey: key);+ expect(+ find.textContaining('Sign in with an invited email'),+ findsOneWidget,+ );+ expect(find.text('[ Sign in ]'), findsOneWidget);+ expect(find.byType(SharedHarnessPanel), findsNothing);+ await tester.pumpWidget(const SizedBox());+ status = 403;+ await show(tester, pinnedKey: key);+ expect(+ find.textContaining('your email has not been invited'),+ findsOneWidget,+ );+ expect(find.byType(SharedHarnessPanel), findsNothing);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'offline links retry automatically and stop retrying when closed',+ (tester) async {+ await show(tester, pinnedKey: key);+ expect(find.textContaining('machine is offline'), findsOneWidget);+ expect(find.byType(SharedHarnessPanel), findsNothing);+ expect(requests.length, 1);+ await tester.pump(const Duration(seconds: 10));+ for (+ var i = 0;+ i < 20 && find.text('Opening shared agent…').evaluate().isNotEmpty;+ i+++ ) {+ await tester.pump(const Duration(milliseconds: 10));+ }+ expect(requests.length, 2);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 20));+ expect(requests.length, 2);+ expect(tester.takeException(), isNull);+ },+ );+}diff --git a/desktop/test/shared_harness_panel_test.dart b/desktop/test/shared_harness_panel_test.dartindex 4a35f2be9..3eb6d8765 100644--- a/desktop/test/shared_harness_panel_test.dart+++ b/desktop/test/shared_harness_panel_test.dart@@ -81,7 +81,7 @@ void main() {},);- for (final width in [1100.0, 620.0]) {+ for (final width in [1100.0, 620.0, 390.0]) {testWidgets('shared pane live output, reconnect, revocation and renewal at width $width',(tester) async {@@ -142,6 +142,17 @@ void main() {),)!,);+ } else if (frame['type'] == 'observer_comments') {+ ws.add(+ jsonEncode({+ 'type': 'observer_comments',+ 'payload': {+ 'requestId': p['requestId'],+ 'comments': [],+ 'canComment': true,+ },+ }),+ );} else if (frame['type'] == 'observer_viewer') {ws.add(jsonEncode({@@ -205,6 +216,27 @@ void main() {await settleNetwork(() => find.text('Live').evaluate().isNotEmpty);expect(requests.first['payload'], containsPair('shareId', 'grant'));expect(find.text('View only'), findsOneWidget);+ await tester.tap(find.text('[ Comments ]'));+ await settleNetwork(+ () => find.byKey(const Key('comment-input')).evaluate().isNotEmpty,+ );+ await tester.enterText(+ find.byKey(const Key('comment-input')),+ 'Keep this draft',+ );+ await tester.tap(find.text('[ Watch ]'));+ await tester.pump();+ await tester.tap(find.text('[ Comments ]'));+ await tester.pump();+ expect(+ tester+ .widget<TextField>(find.byKey(const Key('comment-input')))+ .controller!+ .text,+ 'Keep this draft',+ );+ await tester.tap(find.text('[ Watch ]'));+ await tester.pump();// Receiving the request on the server does not mean its reply has// reached the UI yet. Wait for the response we are about to inspect.await settleNetwork(diff --git a/docs/plans/2026-09-27-007-share-links-and-comments.md b/docs/plans/2026-09-27-007-share-links-and-comments.mdnew file mode 100644index 000000000..df8a17942--- /dev/null+++ b/docs/plans/2026-09-27-007-share-links-and-comments.md@@ -0,0 +1,67 @@+# Share links and comments++Requested: share an agent from desktop or web, copy a public or private link, let recipients view in a browser, and add simple collaboration through comments.++Build on existing owner-authorized E2EE observer sharing. Keep terminal input, control leases, resizing, arbitrary files, and other agents out of the observer protocol.++- One stable HTTPS link per agent, with public/private visibility and Stop sharing. Private is the default. Existing email invitations remain the private allow-list and retain their expiry/revocation behavior; no invitation email service is needed.+- The owner daemon persists link settings and remains the authority on every observer connection. Backend metadata and admission mirror that policy. Private links require an invited account; public viewing requires no login. Visibility changes and revocation disconnect unauthorized viewers.+- Browser links open a dedicated shared-agent view, including while signed out, using the existing shared terminal/viewer renderer. Private sign-in returns to the requested link. Include a clear read-only label and Download app.+- Comments are a small durable thread per agent, stored on the owner machine and transported through the encrypted sharing channel. Viewing works anonymously for public links; posting requires sign-in. Authors can remove their own comments, owners can moderate. Bound text length, history size, message rate, and deduplicate retried submissions.+- Reuse the desktop/web Share control and keep its flow compact: access setting, invited emails when private, Copy link, Stop sharing, and comments. Do not introduce a separate editor, team administration, or terminal co-control.++Verify daemon and backend authorization (public/private/expiry/revocation/cross-account/cross-agent), reconnect and persistence, E2EE boundaries, comments ownership and retry behavior, desktop dialog and browser recipient routes, OAuth return routing, and owner/recipient flows with isolated fixtures. Ship backend, CLI, web/desktop support in the appropriate release order; older daemons must show update guidance.++## Implemented flow++Open **Share** on an agent in desktop or web. Choose **Private** or **Public**, add emails when private, and **Copy link**. The URL remains stable across access changes. Adding an email grants access; the owner sends the copied link themselves. No notification email is sent.++`https://harness.autonomous.ai/s/<link-id>#key=<owner-public-key>` opens a dedicated browser view with **View only**, **Comments**, and **Download app**. The fragment pins the owner's identity before the encrypted handshake. It survives sign-in, refresh, and responsive layout changes. Flutter's automatic hash routing is disabled because this URL is owned by the sharing and sign-in adapters, not workspace dialogs.++Public readers need no account. Private readers sign in with an invited email; another account gets an access message and can switch accounts. Commenting requires sign-in. Threads appear beside live output on wide screens and as a separate view on narrow screens. Readers can select/copy text, delete their own comments, and retry a failed submission without losing the draft or posting it twice. The owner can remove any comment. Changing a public link to private removes uninvited viewers; **Stop sharing** disables the link and revokes the agent's invitations.++The daemon persists authority and comments in `harness-collaboration.json` with atomic writes and private file permissions. Backend `HarnessLink` records contain admission metadata only. Comment payloads travel inside the existing encrypted observer channel and are excluded from frame logs. The daemon checks access for every observer request and output. Guest clients cannot supply their own account identity or send terminal input, resize commands, unrelated agent IDs, or generic owner RPCs.++Limits: 4,000 characters per comment, 200 comments / 1 MiB encoded per thread, and 10 posts per minute per account on a machine. Authors can remove comments to make room. This release is live collaboration: the owner daemon must be online. It does not publish offline snapshots, send emails, or grant terminal control.++## Validation — September 27, 2026++- CLI sharing: 45 tests; 100% statements, branches, functions, and lines. Covers durable settings/comments, retry deduplication, size/rate limits, author/owner moderation, strict observer permissions, and publication recovery.+- Backend sharing: 28 tests; 100% statements, branches, functions, and lines. Full backend suite: 573 passed, 11 skipped. Both TypeScript projects typecheck.+- Desktop/web: 57 targeted tests passed across sharing, comments, pinned identity, offline recovery, OAuth return paths, observer encryption, and WebSocket lifecycle. Focused Flutter analysis is clean. Flutter web release and macOS debug builds succeed.+- Full stack: real backend, disposable MongoDB replica set/Redis, three isolated daemons, tmux, and Chrome. Verified anonymous public viewing, private sign-in return, uninvited-account rejection, browser posting, URL preservation on resize/reload, encrypted terminal/viewer output, forbidden controls, revocation, owner restart persistence, and Stop sharing. Only SSO and the model process are fixtures. No real account credentials or real Harness/Codex home directories are used.+- Visual review: shared dialog and recipient view, including a 390-pixel browser. Comments are readable in the browser accessibility tree.+- Hosting: `/s/:id` rewrite, no-store/no-referrer entry headers, cached assets, callback/download routes, and installer redirects pass against the production Next.js build locally.++Reproduce the daemon/backend coverage gates with `npm run test:sharing` in each folder. From `desktop`, run:++```sh+flutter test --no-pub test/share_harness_test.dart test/shared_harness_panel_test.dart test/harness_comments_test.dart test/shared_agent_page_test.dart test/browser_login_test.dart test/observer_codec_test.dart test/observer_transport_test.dart test/ws_conn_test.dart test/ws_readiness_test.dart+flutter build macos --debug --no-pub --target lib/main.dart+```++For browser E2E, prepare disposable **loopback-only** MongoDB replica-set and Redis services and a JSON file with `mongo` and `redis` URLs. Install Playwright in a test tool directory, with Chrome available. Build/serve the fixture browser from `desktop`:++```sh+flutter build web --release --no-pub --no-wasm-dry-run --no-web-resources-cdn --dart-define=HARNESS_API_URL=http://127.0.0.1:54861 --dart-define=HARNESS_TEST=true --dart-define=HARNESS_CLEAN_PREVIEW=true+python3 scripts/serve-web.py --port 54862+```++In another shell, from `cli`:++```sh+HARNESS_SHARE_E2E_SERVICES=/path/to/disposable-services.json \+HARNESS_SHARE_BACKEND_PORT=54861 \+HARNESS_SHARE_BROWSER_ORIGIN=http://127.0.0.1:54862 \+HARNESS_SHARE_BROWSER_CHECK="$PWD/../desktop/scripts/check-sharing.cjs" \+HARNESS_PLAYWRIGHT_MODULE=/path/to/node_modules/playwright \+HARNESS_SHARE_KEEP=1 npm run test:sharing-e2e+```++The fixture cleans up its daemons, terminals, and browsers. With `HARNESS_SHARE_KEEP=1`, it retains logs and screenshots in the printed temporary directory. The caller owns and discards the disposable database services (including the synthetic databases) and stops the web preview.++## Release dependencies++Release the backend first (Prisma client generation and the existing startup schema/index step), then the owner CLI, then desktop/web. The website hosting repository also needs the `/s/:id` Flutter entry rewrite and the new web-bundle manifest. Keep the usual cache policy: HTML/share/callback entry points are no-store, static assets revalidate. Older daemons keep invitation sharing and show update guidance for browser links/comments.++These validation results describe the local implementation; they do not assert a production release.