Skip to content

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

Connect harness sharing to desktop and isolated viewer streams

Dee847edce15fb8
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index bd782b808..ec9ff92f9 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,3 +1,5 @@
+import type { HarnessShareOwner } from './sharing/owner.js'
+import { SHARE_REQUEST_TYPES, SHARE_RESULT_TYPES } from './sharing/protocol.js'
import { AutonomousDeviceRelay } from './lib/autonomous-device/relay.js'
import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonomous-device/service.js'
/**
@@ -377,6 +379,7 @@ export class BackendSocket {
/** Called on `dsh_remove` — cli.ts uninstalls the harness from this machine. */
onDshRemove: ((id: string) => { ok: true } | { ok: false; error: string; detail: string }) | null = null
/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */
+ harnessSharing: HarnessShareOwner | null = null
dshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = null
private readonly agentCreations = new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations'))
/** Injectable for queue-isolation tests; production uses the machine-local probe. */
@@ -686,6 +689,7 @@ export class BackendSocket {
// default the recap gate to OFF (safe value) instead of holding a stale count — otherwise a turn
// completing during the gap burns a `claude -p` recap that goes nowhere. attachAdapter always
// re-pushes the true count via recomputeAndSendClients on reconnect (and 0→N re-fires the replay).
+ this.harnessSharing?.closeAll()
this.setCommanderCount(0, null) // active count is unknown until the next __clients snapshot
void this.terminalStreams?.closeConnectionsWhere(
(connId) => !isLocalClientId(connId),
@@ -762,6 +766,7 @@ export class BackendSocket {
await this.terminalP2p.stop()
try { this.ws?.close() } catch { /* ignore */ }
this.ws = null
+ await this.harnessSharing?.stop()
}
/** Send an up-frame (event or RPC reply) to the WEB audience. Queued while disconnected.
@@ -797,6 +802,10 @@ export class BackendSocket {
}
/** Send an up-frame to exactly ONE web connection (E2EE pairing/welcome + targeted RPC replies). */
+ sendObserver(connId: string, type: string, payload: Record<string, unknown>): boolean {
+ return this.sendBestEffort({ t: 'up', targetConnId: connId, webEligible: false, commanderEligible: false, frame: { type, payload } })
+ }
+
sendTo(connId: string, frame: Frame): void {
const direct = this.directDeviceSinks.get(connId)
if (direct) { direct(frame); return }
@@ -1105,12 +1114,12 @@ export class BackendSocket {
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = `${type}_result`
// Before the E2EE wrap: an RPC reply is only readable here.
- if (env.LOG_FRAMES && type !== 'agent_read_file' && type !== 'project_preview') logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
+ if (env.LOG_FRAMES && type !== 'agent_read_file' && type !== 'project_preview' && !SHARE_REQUEST_TYPES.has(type)) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
if (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
}
- if (connId && this.e2ee.hasSession(connId) && ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
+ if (connId && this.e2ee.hasSession(connId) && (ENCRYPTED_RPC_RESULT_TYPES.has(resultType) || SHARE_RESULT_TYPES.has(resultType))) {
let replyPayload = payload
if (resultType === 'agent_recent_result') {
const trim = fitRecentReplyPayloadForDevice(
@@ -1133,7 +1142,7 @@ export class BackendSocket {
// adapter plaintext. A real client gets a targeted error; the legacy backend nodeRequest awaiter
// (`connId === ''`) gets a broadcast error with the same requestId so it fails closed without data.
//
- if (ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
+ if ((ENCRYPTED_RPC_RESULT_TYPES.has(resultType) || SHARE_RESULT_TYPES.has(resultType))) {
const errorFrame = { type: resultType, payload: { requestId, error: 'E2EE_REQUIRED' } }
if (connId) this.sendTo(connId, errorFrame)
else this.send(errorFrame)
@@ -1145,6 +1154,11 @@ export class BackendSocket {
private async dispatchDown(frame: Frame, connId: string, transport: 'relay' | 'p2p' = 'relay'): Promise<void> {
const type = frame.type as string | undefined
if (!type) return
+ if (connId.startsWith('observer:')) {
+ await this.harnessSharing?.receive(connId, type, (frame.payload ?? {}) as Record<string, unknown>)
+ return
+ }
+ if (type.startsWith('observer_')) return
const local = this.localClients.has(connId)
// E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.
if (type.startsWith('e2e_')) {
@@ -1161,7 +1175,7 @@ export class BackendSocket {
}
// Client→adapter encrypted frames: chat messages plus trusted web control actions. Plaintext
// passes through for legacy/device transition paths; undecryptable ciphertext is dropped.
- if (!local && isEncryptedDownType(type)) {
+ if (!local && (isEncryptedDownType(type) || SHARE_REQUEST_TYPES.has(type))) {
if (type !== 'message' && type !== 'question_response' && !isWrapped(frame.payload)) {
const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId
if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })
@@ -1179,10 +1193,16 @@ export class BackendSocket {
// than as an opaque __e2e envelope.
// Terminal frames contain raw keystrokes, paste text and screen bytes after
// unwrap. Never pass them to the frame logger, even in diagnostic mode.
- if (env.LOG_FRAMES && !type.startsWith('terminal_') && type !== 'agent_read_file' && type !== 'project_preview') {
+ if (env.LOG_FRAMES && !type.startsWith('terminal_') && type !== 'agent_read_file' && type !== 'project_preview' && !SHARE_REQUEST_TYPES.has(type)) {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)
+ if (SHARE_REQUEST_TYPES.has(type)) {
+ const p = (frame.payload ?? {}) as Record<string, unknown>
+ const result = await this.harnessSharing?.manage(type, p).catch(() => ({ error: 'SHARING_UNAVAILABLE', detail: 'Sharing is temporarily unavailable. Try again.' }))
+ reply(type, p.requestId, result ?? { error: 'UNSUPPORTED' })
+ return
+ }
// Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same
// count; count rise remains the compatibility fallback for older backends.
if (type === '__clients') {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index adcb7ef6c..2f3741679 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1,4 +1,8 @@
#!/usr/bin/env node
+import { HarnessShareOwner } from './sharing/owner.js'
+import { HarnessGrantStore } from './sharing/grants.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'
import { AutonomousDeviceDirect } from './lib/autonomous-device/direct.js'
/**
@@ -2841,6 +2845,27 @@ async function runForeground(session: AuthSession): Promise<void> {
// Built HERE rather than beside the cable stack that also uses it (further down), because the hook
// server starts long before that point and agent restore can sit between the two. A cache bound late
// is a cache that is still null exactly when a cold boot during an outage needs it most.
+ const sharingIdentity = new E2eeStore()
+ sharingIdentity.init()
+ const sharedViewers = new SharedViewerPool((agentId) => {
+ const agent = registry.resolve(agentId)
+ return agent ? backend.dshFrameProvider?.(agent)?.viewerUrl ?? null : null
+ })
+ backend.harnessSharing = new HarnessShareOwner({
+ machineId: () => backend.machineId,
+ identity: sharingIdentity.getIdentity(),
+ grants: new HarnessGrantStore(join(env.ADAPTER_DATA_DIR, 'harness-shares.json')),
+ terminals, resolveAgent: (id) => registry.resolve(id),
+ send: (id, type, payload) => backend.sendObserver(id, type, payload),
+ publish: (method, path, body) => proxyBackend(method, path, body),
+ watchViewer: (id, send) => sharedViewers.watch(id, send),
+ })
+ const shareRelay = new HarnessShareRelay(auth, env.BACKEND_WS_URL, env.AUTONOMOUS_ENV, async () => {
+ const result = await proxyBackend('GET', '/api/harness-shares')
+ if (result.status !== 200) throw new Error('Shared harnesses are temporarily unavailable.')
+ return ((result.body as { data?: { machines?: SharedMachineReference[] } }).data?.machines ?? [])
+ })
+
const machineListCache = new MachineListCache(
() => proxyBackend('GET', '/api/machines'),
computerId,
@@ -3257,6 +3282,7 @@ async function runForeground(session: AuthSession): Promise<void> {
onMachineRename: (machineId, name) => proxyBackend('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { name }),
onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),
onAuthMe: () => proxyBackend('GET', '/api/auth/me'),
+ onSharedHarnesses: () => proxyBackend('GET', '/api/harness-shares'),
onStore: (method, path, body) => proxyBackend(method, path, body),
})
// Claim the pid file for OURSELVES, and only now that the control port is bound. It used to be
@@ -3295,6 +3321,7 @@ async function runForeground(session: AuthSession): Promise<void> {
})
const localWsServer = attachLocalWsServer(hookServer, {
+ shareRelay,
// The window and the dial are one desk: opening an agent in the app brings the dial to it, switching
// the dial's machine first when the app moved to another one.
onAppFocusState: (machineId, agentId, connId, expectedRevision) => {
@@ -4573,6 +4600,8 @@ async function runForeground(session: AuthSession): Promise<void> {
;(hookServer as unknown as { closeAllConnections?: () => void }).closeAllConnections?.()
// Release the fixed hook port before the child binds. Process-owned agents stay in the persisted
// registry and are revalidated by the new daemon's first discovery passes.
+ shareRelay.close()
+ sharedViewers.stop()
await localWsServer.close()
hookServer.close()
shutdownSummaryPool()
@@ -4715,6 +4744,8 @@ async function runForeground(session: AuthSession): Promise<void> {
for (const r of devinReaders.values()) r.stop()
await cursorDiscovery.stop()
await watcher.stop()
+ shareRelay.close()
+ sharedViewers.stop()
await localWsServer.close()
hookServer.close()
shutdownSummaryPool()
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index d00590fbd..7e981e9c6 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -119,6 +119,7 @@ export interface HookServerHandlers {
onMachineDelete?: (machineId: string) => Promise<PairOutcome>
/** GET /api/auth/me — proxy the signed-in user's profile from backend. */
onAuthMe?: () => Promise<PairOutcome>
+ onSharedHarnesses?: () => Promise<PairOutcome>
/** /api/store/* — proxy the Harness Store's ratings and reviews to backend the same way: reads
* ungated like the machine list, writes (PUT/DELETE) CSRF-guarded like a rename. See storeProxy.ts. */
onStore?: StoreHandler
@@ -606,6 +607,10 @@ export function startHookServer(
if (!list) { json(503, { error: 'UNAVAILABLE' }); return }
await proxied(list); return
}
+ if (req.method === 'GET' && url === '/api/harness-shares') {
+ if (!handlers.onSharedHarnesses) { json(503, { error: 'UNAVAILABLE' }); return }
+ await proxied(handlers.onSharedHarnesses); return
+ }
if (req.method === 'GET' && url === '/api/auth/me') {
const me = handlers.onAuthMe
if (!me) { json(503, { error: 'UNAVAILABLE' }); return }
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index 60637721d..2c381d5ce 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -1,3 +1,4 @@
+import { SHARE_REQUEST_TYPES } from '../../sharing/protocol.js'
/**
* The "client" (formerly-browser) role of the E2EE session protocol, run by THIS daemon on behalf of a
* local app relaying through it to a REMOTE machine it has `harness link connect`-ed to via that
@@ -103,7 +104,7 @@ export class RelaySessionCrypto {
/** Encrypt an outgoing (local app → remote machine) frame if its type requires it. */
wrapOutgoing(frame: Frame): Frame {
const type = frame.type as string | undefined
- if (!type || !this.c2s || !C.isEncryptedDownType(type)) return frame
+ if (!type || !this.c2s || !(C.isEncryptedDownType(type) || SHARE_REQUEST_TYPES.has(type))) return frame
const payload = C.wrapPayload(this.c2s, 'p', this.c2sCounter++, type, undefined, frame.payload)
return { ...frame, payload }
}
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 345745070..e86772752 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -1,3 +1,4 @@
+import { SharingEndedError, type HarnessShareRelay } from './sharing/relay.js'
import { randomUUID } from 'node:crypto'
import type { AppSwarms } from './cable/cableSession.js'
import type http from 'node:http'
@@ -39,6 +40,7 @@ export interface LocalWsServerOptions {
/** Serves a `machine_select` for any OTHER machine this signed-in user owns, by relaying to
* backend's `/api/web-ws` — see lib/remoteRelay.ts. Omit to keep today's own-machine-only behavior. */
relayPool?: RemoteRelayPool
+ shareRelay?: HarnessShareRelay
autonomousEnv?: string
/** The desktop app opened an agent's terminal — which agent, and on which machine. Lets the dial follow
* the window, so the two screens stay one desk. */
@@ -260,6 +262,18 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
close(4403, 'machine mismatch')
return
}
+ if (typeof payload.shareId === 'string') {
+ if (!options.shareRelay) { close(4403, 'Sharing is unavailable'); return }
+ try {
+ relay = await options.shareRelay.acquire(requestedMachineId, payload.shareId, sink, close)
+ if (ws.readyState !== WebSocket.OPEN) { relay.detach(); return }
+ selected = true
+ } catch (error) {
+ close(error instanceof SharingEndedError ? 4403 : 1013,
+ error instanceof Error ? error.message.slice(0, 120) : 'Sharing unavailable')
+ }
+ return
+ }
if (requestedMachineId === options.machineId) {
if (!options.backend.registerLocalClient(connId, sink)) {
close(1011, 'local registration failed')
diff --git a/cli/src/sharing/grants.ts b/cli/src/sharing/grants.ts
index a96e96e06..a22eaf5ea 100644
--- a/cli/src/sharing/grants.ts
+++ b/cli/src/sharing/grants.ts
@@ -13,6 +13,7 @@ const grantSchema = z.object({
recipientEmail: emailSchema, name: z.string(), engine: z.string().nullable(),
ownerPublicKey: z.string(), expiresAt: z.string().datetime(), createdAt: z.string().datetime(),
revoked: z.boolean().default(false), pending: z.boolean().default(false),
+ publicationError: z.string().nullable().default(null),
})
export type HarnessGrant = z.infer<typeof grantSchema>
@@ -36,23 +37,26 @@ export class HarnessGrantStore {
all(): HarnessGrant[] { return this.grants.map(g => ({ ...g })) }
active(id: string, email: string, machineId: string): HarnessGrant | null {
const grant = this.grants.find(g => g.id === id && g.machineId === machineId
- && g.recipientEmail === email && !g.revoked && Date.parse(g.expiresAt) > this.now())
+ && g.recipientEmail === email && !g.revoked && !g.publicationError && Date.parse(g.expiresAt) > this.now())
return grant ? { ...grant } : null
}
list(machineId: string, agentId: string): HarnessGrant[] {
return this.all().filter(g => g.machineId === machineId && g.agentId === agentId && !g.revoked)
}
- invite(input: Omit<HarnessGrant, 'id' | 'createdAt' | 'pending' | 'revoked'>): HarnessGrant {
+ invite(input: Omit<HarnessGrant, 'id' | 'createdAt' | 'pending' | 'revoked' | 'publicationError'>): HarnessGrant {
const previous = this.grants.find(g => g.machineId === input.machineId && g.agentId === input.agentId
&& g.recipientEmail === input.recipientEmail)
const grant = grantSchema.parse({ ...input, id: previous?.id ?? randomUUID(),
- createdAt: previous?.createdAt ?? new Date(this.now()).toISOString(), pending: true, revoked: false })
+ createdAt: previous?.createdAt ?? new Date(this.now()).toISOString(), pending: true, revoked: false, publicationError: null })
this.save([...this.grants.filter(g => g.id !== grant.id), grant])
return { ...grant }
}
synced(id: string): void {
this.save(this.grants.map(g => g.id === id ? { ...g, pending: false } : g))
}
+ failed(id: string, publicationError: string): void {
+ this.save(this.grants.map(g => g.id === id ? { ...g, pending: false, publicationError } : g))
+ }
revoke(id: string, machineId: string, agentId: string): boolean {
const found = this.grants.some(g => g.id === id && g.machineId === machineId && g.agentId === agentId)
if (found) this.save(this.grants.map(g => g.id === id ? { ...g, revoked: true, pending: true } : g))
diff --git a/cli/src/sharing/owner.spec.ts b/cli/src/sharing/owner.spec.ts
new file mode 100644
index 000000000..eb5cda81b
--- /dev/null
+++ b/cli/src/sharing/owner.spec.ts
@@ -0,0 +1,224 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { b64e, newEphemeral, newIdentity } from '../lib/e2ee/core.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinator.js'
+import type { TerminalStreamSink } from '../lib/terminalTypes.js'
+import { decodeTerminalLocal, TerminalBinaryKind } from '../lib/terminalBinary.js'
+import { HarnessGrantStore } from './grants.js'
+import { HarnessShareOwner } from './owner.js'
+import { recipientHandshake, type ObserverCipher } from './crypto.js'
+
+describe('owner authority and read-only observation', () => {
+ let root: string, store: HarnessGrantStore, owner: HarnessShareOwner
+ const identity = newIdentity()
+ let frames: Array<{ id: string; type: string; payload: any }>
+ let agents: Map<string, RegisteredSession>
+ let publish: ReturnType<typeof vi.fn>, send: ReturnType<typeof vi.fn>, watchViewer: ReturnType<typeof vi.fn>
+ let opened: Array<{ sink: TerminalStreamSink; handle: any }>
+ let machineId: string
+ beforeEach(() => {
+ vi.useFakeTimers()
+ root = mkdtempSync(join(tmpdir(), 'share-owner-test-'))
+ store = new HarnessGrantStore(join(root, 'grants.json'))
+ frames = []; opened = []; machineId = 'machine'
+ agents = new Map([['agent', { agentId: 'agent', sessionId: 's', engine: 'codex',
+ active: true, projectPath: '/tmp/project', runtimes: [{ backend: 'tmux', paneId: '%1' }],
+ primaryRuntimeKey: 'tmux:default:%1' } as RegisteredSession]])
+ publish = vi.fn(async () => ({ status: 200, body: {} }))
+ send = vi.fn((id, type, payload) => { frames.push({ id, type, payload }); return true })
+ watchViewer = vi.fn((_id, callback) => { callback({ state: 'live', data: 'jpeg' }); return vi.fn() })
+ owner = new HarnessShareOwner({ machineId: () => machineId, identity, grants: store,
+ resolveAgent: id => agents.get(id), send, publish, watchViewer,
+ terminals: { openStream: async (_agent, _size, sink, readOnly) => {
+ expect(readOnly).toBe(true)
+ const handle = { runtime: { backend: 'tmux', paneId: '%1' },
+ snapshot: vi.fn(async () => ({ state: 'succeeded', value: { bytes: Buffer.from('hello'), cols: 120, rows: 40 } })),
+ beginSnapshot: vi.fn(), endSnapshot: vi.fn(), close: vi.fn(async () => {}),
+ writeRaw: vi.fn(), pasteRaw: vi.fn(), resize: vi.fn(), scroll: vi.fn(),
+ pauseOutput: vi.fn(async () => ({ state: 'succeeded' })), resumeOutput: vi.fn(async () => ({ state: 'succeeded' })) }
+ opened.push({ sink, handle })
+ return { state: 'succeeded', value: handle }
+ } } as unknown as TerminalBackendCoordinator,
+ })
+ })
+ afterEach(async () => { await owner.stop(); vi.useRealTimers(); rmSync(root, { recursive: true, force: true }) })
+ async function invite(emails = ['[email protected]']) {
+ return owner.manage('harness_share_invite', { agentId: 'agent', emails })
+ }
+ async function connect(email = '[email protected]', id = 'observer:ken') {
+ const grant = store.list('machine', 'agent').find(g => g.recipientEmail === email)!
+ const ephemeral = newEphemeral()
+ await owner.receive(id, 'observer_open', { shareId: grant.id, email, ephemeral: b64e(ephemeral.pub) })
+ const welcome = frames.findLast(f => f.id === id && f.type === 'observer_welcome')!
+ const cipher = recipientHandshake(ephemeral, 'machine', grant.id, b64e(identity.pub), welcome.payload)
+ return { id, cipher, grant }
+ }
+ async function request(client: { id: string; cipher: ObserverCipher }, 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 }) {
+ const list = frames.filter(f => f.id === client.id && f.type === 'observer_frame')
+ frames = frames.filter(f => f.id !== client.id || f.type !== 'observer_frame')
+ return list.map(f => client.cipher.open(f.payload) as any)
+ }
+ it('validates management, normalizes duplicate emails and preserves invitation IDs on renewal', async () => {
+ expect(await owner.manage('harness_share_list', {})).toMatchObject({ error: 'HARNESS_NOT_FOUND' })
+ expect(await owner.manage('wrong', { agentId: 'agent' })).toMatchObject({ error: 'UNSUPPORTED' })
+ expect(await invite(['bad'])).toMatchObject({ error: 'INVALID_INVITATION' })
+ const result = await invite([' [email protected] ', '[email protected]', '[email protected]'])
+ expect(result.shares).toHaveLength(2)
+ expect(publish).toHaveBeenCalledTimes(2)
+ const first = store.all()[0]
+ expect(first.pending).toBe(false)
+ expect(first.recipientEmail).toBe('[email protected]')
+ await invite()
+ expect(store.all().find(g => g.recipientEmail === first.recipientEmail)?.id).toBe(first.id)
+ expect(await owner.manage('harness_share_remove', { agentId: 'agent', id: 'missing' })).toMatchObject({ error: 'INVITATION_NOT_FOUND' })
+ })
+ it('gives two observers independent streams and only read capabilities, with no control or resizing', async () => {
+ await invite(['[email protected]', '[email protected]'])
+ const ken = await connect(), diego = await connect('[email protected]', 'observer:diego')
+ for (const client of [ken, diego]) {
+ await request(client, 'terminal_capabilities', { requestId: 'cap' })
+ const capabilities = read(client)[0].payload
+ expect(capabilities.engines.every((e: any) => !e.input && !e.resize && !e.mouse && !e.paste)).toBe(true)
+ await request(client, 'terminal_open', { requestId: 'open', protocolVersion: 3, agentId: 'agent', cols: 200, rows: 100 })
+ const received = read(client)
+ expect(received[0]).toMatchObject({ type: 'terminal_ready', payload: { readOnly: true } })
+ const keyframe = decodeTerminalLocal(Buffer.from(received[1].payload.bytes, 'base64'))
+ expect(keyframe?.kind).toBe(TerminalBinaryKind.keyframe)
+ expect(Buffer.from(keyframe!.bytes).toString()).toBe('hello')
+ }
+ expect(opened).toHaveLength(2)
+ opened[0].sink.onData(Buffer.from('live update'))
+ await vi.advanceTimersByTimeAsync(8)
+ expect(read(ken)).toHaveLength(1)
+ expect(read(diego)).toHaveLength(0)
+ for (const type of ['terminal_input', 'terminal_resize', 'terminal_paste', 'terminal_takeover',
+ 'terminal_scroll', 'send', 'answer', 'read_file', 'list_agents', 'delete_agent', 'harness_share_invite']) {
+ await request(ken, type, { agentId: 'agent', requestId: type })
+ expect(read(ken)[0]).toMatchObject({ type: 'terminal_error', payload: { code: 'VIEW_ONLY', requestId: type } })
+ }
+ for (const payload of [{ agentId: 'unshared' }, {}]) {
+ await request(ken, 'terminal_open', payload)
+ expect(read(ken)[0].payload.code).toBe('VIEW_ONLY')
+ }
+ for (const { handle } of opened) {
+ expect(handle.writeRaw).not.toHaveBeenCalled(); expect(handle.pasteRaw).not.toHaveBeenCalled()
+ expect(handle.resize).not.toHaveBeenCalled(); expect(handle.scroll).not.toHaveBeenCalled()
+ }
+ expect((await owner.manage('harness_share_list', { agentId: 'agent' })).shares).toEqual(
+ expect.arrayContaining([expect.objectContaining({ email: '[email protected]', watching: 1 })]))
+ })
+ it('streams viewer pixels once per observer and immediately closes a revoked viewer', async () => {
+ await invite()
+ const client = await connect()
+ await request(client, 'observer_viewer')
+ await request(client, 'observer_viewer')
+ expect(watchViewer).toHaveBeenCalledTimes(1)
+ expect(read(client)[0]).toMatchObject({ type: 'observer_viewer', payload: { data: 'jpeg' } })
+ publish.mockRejectedValue(new Error('offline'))
+ expect((await owner.manage('harness_share_remove', { agentId: 'agent', id: client.grant.id })).shares).toEqual([])
+ expect(watchViewer.mock.results[0].value).toHaveBeenCalledTimes(1)
+ expect(frames.at(-1)).toMatchObject({ type: 'observer_closed', payload: { reason: 'Access removed', retry: false } })
+ expect(new HarnessGrantStore(join(root, 'grants.json')).active(client.grant.id, '[email protected]', 'machine')).toBeNull()
+ watchViewer.mock.calls[0][1]({ data: 'late pixels' })
+ expect(read(client)).toEqual([])
+ await owner.receive(client.id, 'observer_open', { shareId: client.grant.id, email: '[email protected]' })
+ expect(frames.at(-1)?.type).toBe('observer_closed')
+ })
+ it('fails closed for forged, replayed, wrong-email and malformed observer frames', async () => {
+ await invite()
+ const client = await connect()
+ await owner.receive('ordinary-client', 'observer_open', {})
+ await owner.receive('observer:unknown', 'observer_frame', {})
+ const before = frames.length
+ await owner.receive('observer:bad', 'observer_open', { shareId: client.grant.id, email: '[email protected]' })
+ await owner.receive('observer:bad', 'observer_open', { shareId: client.grant.id, email: '[email protected]', ephemeral: 'bad' })
+ expect(frames.slice(before).every(f => f.type === 'observer_closed')).toBe(true)
+ const packet = client.cipher.seal({ type: 'terminal_capabilities', payload: {} })
+ await owner.receive(client.id, 'observer_frame', packet as any)
+ await owner.receive(client.id, 'observer_frame', packet as any)
+ expect(frames.at(-1)?.payload.reason).toBe('Invalid observer message')
+ for (const value of [{}, { type: 4, payload: {} }, { type: 'terminal_open' }]) {
+ const c = await connect('[email protected]', `observer:${JSON.stringify(value)}`)
+ await owner.receive(c.id, 'observer_frame', c.cipher.seal(value) as any)
+ expect(frames.at(-1)?.payload.reason).toBe('Invalid observer message')
+ }
+ const c = await connect('[email protected]', 'observer:repeated')
+ await owner.receive(c.id, 'observer_open', {})
+ expect(frames.at(-1)?.payload.reason).toBe('Invalid observer handshake')
+ const d = await connect('[email protected]', 'observer:other-type')
+ await owner.receive(d.id, 'shell', {})
+ expect(frames.at(-1)?.payload.reason).toBe('Invalid observer message')
+ })
+ it('closes on expiry, deleted harness, changed machine, and failed transport', async () => {
+ await invite()
+ const c = await connect()
+ agents.clear()
+ await request(c, 'observer_viewer')
+ expect(frames.at(-1)?.type).toBe('observer_closed')
+ agents.set('agent', { agentId: 'agent', engine: 'codex' } as RegisteredSession)
+ const d = await connect('[email protected]', 'observer:expired')
+ vi.setSystemTime(Date.now() + 31 * 86400_000)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(frames.findLast(f => f.id === d.id)?.type).toBe('observer_closed')
+ await invite()
+ const e = await connect('[email protected]', 'observer:machine')
+ machineId = 'another-machine'
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(frames.findLast(f => f.id === e.id)?.type).toBe('observer_closed')
+ machineId = 'machine'
+ send.mockReturnValue(false)
+ const grant = store.all()[0]
+ await owner.receive('observer:failed', 'observer_open', { shareId: grant.id, email: grant.recipientEmail, ephemeral: b64e(newEphemeral().pub) })
+ expect((await owner.manage('harness_share_list', { agentId: 'agent' })).shares).toEqual([expect.objectContaining({ watching: 0 })])
+ })
+ it('retains pending changes through outages, reports permanent failures and retries durable revocation', async () => {
+ publish.mockResolvedValue({ status: 503, body: {} })
+ expect((await invite()).shares).toEqual([expect.objectContaining({ pending: true })])
+ publish.mockResolvedValue({ status: 400, body: { error: { message: 'You already own this harness.' } } })
+ await owner.sync()
+ const failed = store.all()[0]
+ expect(failed.publicationError).toBe('You already own this harness.')
+ expect(store.active(failed.id, failed.recipientEmail, 'machine')).toBeNull()
+ publish.mockResolvedValue({ status: 403, body: {} })
+ await invite()
+ expect(store.all()[0].publicationError).toContain('could not be shared')
+ publish.mockResolvedValue({ status: 200, body: {} })
+ await invite()
+ expect(store.all()[0].publicationError).toBeNull()
+ publish.mockResolvedValue({ status: 404, body: {} })
+ await owner.manage('harness_share_remove', { agentId: 'agent', id: failed.id })
+ expect(store.all()[0]).toMatchObject({ revoked: true, pending: false })
+ })
+ it('serializes invitation changes, and a removal during a pending publication cannot be lost', async () => {
+ await invite()
+ const grant = store.all()[0]
+ store.invite(grant)
+ let finish!: (value: { status: number; body: {} }) => void
+ publish.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ const syncing = owner.sync()
+ expect(owner.sync()).toBe(syncing)
+ const remove = owner.manage('harness_share_remove', { agentId: 'agent', id: grant.id })
+ await Promise.resolve()
+ expect(store.all()[0].revoked).toBe(true)
+ finish({ status: 200, body: {} })
+ await remove
+ expect(publish.mock.calls.at(-1)?.[0]).toBe('DELETE')
+ expect(store.all()[0]).toMatchObject({ revoked: true, pending: false })
+ })
+ it('marks owner disconnects as recoverable and releases explicit departures', async () => {
+ await invite()
+ const c = await connect()
+ await owner.receive(c.id, 'observer_close', {})
+ expect(frames.at(-1)?.payload.retry).toBe(false)
+ await connect('[email protected]', 'observer:again')
+ owner.closeAll()
+ expect(frames.at(-1)?.payload).toMatchObject({ reason: 'Owner disconnected', retry: true })
+ owner.close('observer:already-gone')
+ })
+})
diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.ts
index c76828ec8..a64e10e53 100644
--- a/cli/src/sharing/owner.ts
+++ b/cli/src/sharing/owner.ts
@@ -59,14 +59,14 @@ export class HarnessShareOwner {
if (!observer || !this.authorized(observer)) return false
return this.deps.send(connId, 'observer_frame', observer.cipher.seal(frame) as unknown as Payload)
}
- close(connId: string, reason = 'Observation ended'): void {
+ close(connId: string, reason = 'Observation ended', retry = false): void {
if (!this.observers.delete(connId)) return
this.viewers.get(connId)?.()
this.viewers.delete(connId)
void this.streams.closeConnection(connId)
- this.deps.send(connId, 'observer_closed', { reason })
+ this.deps.send(connId, 'observer_closed', { reason, retry })
}
- closeAll(): void { for (const id of this.observers.keys()) this.close(id, 'Owner disconnected') }
+ closeAll(): void { for (const id of this.observers.keys()) this.close(id, 'Owner disconnected', true) }
async stop(): Promise<void> { clearInterval(this.timer); this.closeAll(); await this.streams.stop() }
async receive(connId: string, type: string, payload: Payload): Promise<void> {
@@ -130,17 +130,19 @@ export class HarnessShareOwner {
ownerPublicKey: b64e(this.deps.identity.pub),
expiresAt: new Date(this.now() + parsed.data.days * 86400_000).toISOString() })
}
+ await this.syncing
await this.sync()
} else if (type === 'harness_share_remove') {
if (typeof payload.id !== 'string' || !this.deps.grants.revoke(payload.id, machineId, agentId)) {
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')
+ await this.syncing
await this.sync()
} else if (type !== 'harness_share_list') return { error: 'UNSUPPORTED' }
return { 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,
+ 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,
})) }
}
@@ -157,6 +159,12 @@ export class HarnessShareOwner {
// A revoke may have happened while this network request was in flight.
const current = this.deps.grants.all().find(g => g.id === grant.id)
if (current?.revoked === grant.revoked && current.expiresAt === grant.expiresAt) this.deps.grants.synced(grant.id)
+ } else if (!grant.revoked && [400, 403, 409, 422].includes(result.status)) {
+ const body = result.body as { error?: { message?: string }; message?: string }
+ const current = this.deps.grants.all().find(g => g.id === grant.id)
+ if (current && !current.revoked && current.expiresAt === grant.expiresAt) {
+ this.deps.grants.failed(grant.id, body.error?.message || body.message || 'This invitation could not be shared. Remove it or add the email again to retry.')
+ }
}
} catch { /* Persisted pending change is retried, including after daemon restart. */ }
}
diff --git a/cli/src/sharing/protocol.ts b/cli/src/sharing/protocol.ts
new file mode 100644
index 000000000..8c0bc2ded
--- /dev/null
+++ b/cli/src/sharing/protocol.ts
@@ -0,0 +1,3 @@
+/** 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_RESULT_TYPES = new Set([...SHARE_REQUEST_TYPES].map(type => `${type}_result`))
diff --git a/cli/src/sharing/relay.ts b/cli/src/sharing/relay.ts
new file mode 100644
index 000000000..088ffb43e
--- /dev/null
+++ b/cli/src/sharing/relay.ts
@@ -0,0 +1,98 @@
+import { WebSocket } from 'ws'
+import { b64e, newEphemeral } from '../lib/e2ee/core.js'
+import type { AuthSessionManager } from '../lib/authSession.js'
+import type { Frame, LocalClientSink } from '../backendSocket.js'
+import type { RelaySession } from '../lib/remoteRelay.js'
+import { recipientHandshake, type ObserverCipher } from './crypto.js'
+import { watchSocketLiveness } from '../lib/wsLiveness.js'
+
+export interface SharedHarnessReference {
+ id: string; agentId: string; name: string; engine: string | null; ownerPublicKey: string; expiresAt: string
+}
+export interface SharedMachineReference {
+ machineId: string; name: string | null; ownerName: string; status: string; shares: SharedHarnessReference[]
+}
+
+export class SharingEndedError extends Error {}
+
+/** One invitation per connection. Never promoted into a full machine link or a shared connection pool. */
+export class HarnessShareRelay {
+ private sessions = new Set<() => void>()
+ constructor(private readonly auth: AuthSessionManager, private readonly backendWsBase: string,
+ private readonly environment: string, private readonly discover: () => Promise<SharedMachineReference[]>) {}
+ async acquire(machineId: string, shareId: string, sink: LocalClientSink,
+ onClosed: (code: number, reason: string) => void): Promise<RelaySession> {
+ const machines = await this.discover()
+ const machine = machines.find(m => m.machineId === machineId)
+ const share = machine?.shares.find(s => s.id === shareId)
+ if (!share) throw new SharingEndedError('Sharing ended or invitation expired')
+ const token = await this.auth.accessToken()
+ const url = `${this.backendWsBase.replace(/\/$/, '')}/api/observer-ws?share=${encodeURIComponent(shareId)}&autonomousEnv=${encodeURIComponent(this.environment)}`
+ const ws = new WebSocket(url, [token], { handshakeTimeout: 10_000, maxPayload: 3 * 1024 * 1024 })
+ const ephemeral = newEphemeral()
+ let cipher: ObserverCipher | null = null, detached = false, settled = false
+ let heartbeat: ReturnType<typeof watchSocketLiveness> | null = null
+ const detach = () => { detached = true; heartbeat?.stop(); this.sessions.delete(detach); ws.terminate() }
+ this.sessions.add(detach)
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => { reject(new Error('The owner’s machine is not responding.')); detach() }, 15_000)
+ const ready = () => {
+ if (settled) return
+ settled = true; clearTimeout(timeout)
+ sink.sendFrame({ type: 'connected', payload: { machineId, e2ee: false, readOnly: true } })
+ resolve()
+ }
+ ws.on('error', () => { if (!settled) { clearTimeout(timeout); reject(new Error('Could not connect to the shared harness.')) } })
+ ws.on('close', (code, reason) => {
+ clearTimeout(timeout); heartbeat?.stop(); this.sessions.delete(detach)
+ if (!settled) reject(new Error(reason.toString() || 'The owner’s machine is offline.'))
+ if (!detached) onClosed(code === 4403 ? 4403 : 1012, reason.toString() || 'Owner disconnected')
+ })
+ ws.on('open', () => { heartbeat = watchSocketLiveness(ws) })
+ ws.on('message', raw => {
+ try {
+ const frame = JSON.parse(raw.toString()) as { type: string; payload: Record<string, unknown> }
+ if (frame.type === 'observer_connected') {
+ ws.send(JSON.stringify({ type: 'observer_hello', payload: { ephemeral: b64e(ephemeral.pub) } }))
+ } else if (frame.type === 'observer_welcome' && !cipher) {
+ cipher = recipientHandshake(ephemeral, machineId, shareId, share.ownerPublicKey, frame.payload)
+ ready()
+ } else if (frame.type === 'observer_closed') {
+ onClosed(frame.payload?.retry === true ? 1012 : 4403, String(frame.payload?.reason || 'Sharing ended')); detach()
+ if (!settled) { clearTimeout(timeout); reject(new Error('Sharing ended')) }
+ } else if (frame.type === 'observer_frame' && cipher) {
+ const clear = cipher.open(frame.payload)
+ if (!clear) { onClosed(1011, 'Shared harness verification failed'); detach(); return }
+ if (clear.type === 'observer_binary') {
+ const bytes = (clear.payload as { bytes?: unknown })?.bytes
+ if (typeof bytes === 'string') sink.sendBinary(Buffer.from(bytes, 'base64'))
+ } else sink.sendFrame(clear)
+ }
+ } catch {
+ clearTimeout(timeout)
+ if (settled) onClosed(1011, 'The shared harness identity could not be verified.')
+ reject(new Error('The shared harness identity could not be verified.')); detach()
+ }
+ })
+ })
+ } catch (error) { detach(); throw error }
+ return {
+ send: async (frame: Frame) => {
+ if (!cipher || detached || ws.readyState !== WebSocket.OPEN) return
+ // 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))) {
+ sink.sendFrame({ type: `${String(frame.type)}_result`, payload: {
+ requestId: (frame.payload as { requestId?: unknown })?.requestId, error: 'VIEW_ONLY',
+ } }); return
+ }
+ ws.send(JSON.stringify({ type: 'observer_frame', payload: cipher.seal(frame) }))
+ },
+ sendBinary: async () => { /* Observers never send terminal bytes. */ },
+ detach,
+ }
+ }
+ close(): void { for (const stop of [...this.sessions]) stop() }
+}
diff --git a/cli/src/sharing/viewer.ts b/cli/src/sharing/viewer.ts
new file mode 100644
index 000000000..97064ab22
--- /dev/null
+++ b/cli/src/sharing/viewer.ts
@@ -0,0 +1,153 @@
+import { spawn, type ChildProcess } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { WebSocket } from 'ws'
+
+type Payload = Record<string, unknown>
+type Listener = (frame: Payload) => void
+
+export function viewerTarget(value: string | null): string | null {
+ try {
+ const url = new URL(value ?? '')
+ if (url.protocol !== 'http:' || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
+ || !url.port || url.username || url.password) return null
+ return url.href
+ } catch { return null }
+}
+
+export function viewerBrowser(): string | null {
+ const paths = [process.env.HARNESS_VIEWER_BROWSER,
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
+ '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome']
+ return paths.find((p): p is string => !!p && existsSync(p)) ?? null
+}
+
+/** A private, credential-free renderer. Only JPEGs cross the sharing boundary, never HTTP requests. */
+export class ViewerCapture {
+ private child: ChildProcess | null = null
+ private ws: WebSocket | null = null
+ private directory: string | null = null
+ private id = 0
+ private pending = new Map<number, { resolve: (value: Payload) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }>()
+ private closed = false
+ private session = ''
+ async start(url: string): Promise<void> {
+ const target = viewerTarget(url), browser = viewerBrowser()
+ if (!target) throw new Error('This harness has no live viewer yet.')
+ if (!browser) throw new Error('The owner needs Chrome or Chromium to share this viewer.')
+ this.directory = await mkdtemp(join(tmpdir(), 'harness-shared-viewer-'))
+ if (this.closed) { await this.stop(); return }
+ this.child = spawn(browser, ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
+ '--disable-sync', '--disable-extensions', '--disable-background-networking', '--mute-audio',
+ '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0',
+ `--user-data-dir=${this.directory}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] })
+ const endpoint = await new Promise<string>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('The live viewer took too long to start.')), 15_000)
+ let buffer = ''
+ this.child!.stderr!.on('data', (bytes: Buffer) => {
+ buffer = (buffer + bytes.toString()).slice(-8192)
+ const match = /DevTools listening on (ws:\/\/[^\s]+)/.exec(buffer)
+ if (match) { clearTimeout(timer); resolve(match[1]) }
+ })
+ this.child!.once('error', () => { clearTimeout(timer); reject(new Error('The live viewer could not start.')) })
+ this.child!.once('exit', () => { clearTimeout(timer); reject(new Error('The live viewer stopped.')); this.failPending() })
+ })
+ if (this.closed) return
+ this.ws = new WebSocket(endpoint, { handshakeTimeout: 5000, maxPayload: 4 * 1024 * 1024 })
+ this.ws.on('error', () => this.failPending())
+ this.ws.on('close', () => this.failPending())
+ this.ws.on('message', raw => {
+ let message: { id?: number; result?: Payload; error?: unknown }
+ try { message = JSON.parse(raw.toString()) } catch { return }
+ const entry = this.pending.get(message.id ?? -1)
+ if (!entry) return
+ this.pending.delete(message.id!); clearTimeout(entry.timer)
+ if (message.error) entry.reject(new Error('The viewer could not render this frame.'))
+ else entry.resolve(message.result ?? {})
+ })
+ await new Promise<void>((resolve, reject) => {
+ this.ws!.once('open', resolve); this.ws!.once('error', () => reject(new Error('The viewer renderer disconnected.')))
+ })
+ const page = await this.call('Target.createTarget', { url: 'about:blank' })
+ const attached = await this.call('Target.attachToTarget', { targetId: page.targetId, flatten: true })
+ this.session = String(attached.sessionId)
+ await this.call('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false })
+ await this.call('Page.enable')
+ const navigation = await this.call('Page.navigate', { url: target })
+ if (navigation.errorText) throw new Error('The owner’s viewer is not answering yet.')
+ }
+ private call(method: string, params: Payload = {}): Promise<Payload> {
+ return new Promise((resolve, reject) => {
+ if (this.closed || this.ws?.readyState !== WebSocket.OPEN) { reject(new Error('The viewer renderer disconnected.')); return }
+ const id = ++this.id
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('The viewer is taking too long to respond.')) }, 8000)
+ this.pending.set(id, { resolve, reject, timer })
+ this.ws.send(JSON.stringify({ id, method, params, ...(this.session ? { sessionId: this.session } : {}) }))
+ })
+ }
+ async capture(): Promise<string> {
+ const result = await this.call('Page.captureScreenshot', { format: 'jpeg', quality: 75, captureBeyondViewport: false })
+ if (typeof result.data !== 'string' || result.data.length > 2 * 1024 * 1024) throw new Error('This viewer frame is too large.')
+ return result.data
+ }
+ private failPending(): void {
+ for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error('The viewer renderer disconnected.')) }
+ this.pending.clear()
+ }
+ async stop(): Promise<void> {
+ this.closed = true; this.failPending(); this.ws?.terminate(); this.ws = null
+ const child = this.child; this.child = null
+ if (child && child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGTERM')
+ await new Promise<void>(resolve => {
+ const timer = setTimeout(() => { child.kill('SIGKILL'); resolve() }, 3000)
+ child.once('exit', () => { clearTimeout(timer); resolve() })
+ })
+ }
+ const directory = this.directory; this.directory = null
+ if (directory) await rm(directory, { recursive: true, force: true }).catch(() => {})
+ }
+}
+
+/** One renderer per watched harness, shared by all observers; released when its last watcher leaves. */
+export class SharedViewerPool {
+ private entries = new Map<string, { listeners: Set<Listener>; stop: () => void }>()
+ constructor(private readonly target: (agentId: string) => string | null,
+ private readonly create = () => new ViewerCapture()) {}
+ watch(agentId: string, listener: Listener): () => void {
+ const existing = this.entries.get(agentId)
+ if (existing) { existing.listeners.add(listener); return () => this.remove(agentId, listener) }
+ if (this.entries.size >= 8) { listener({ state: 'unavailable', message: 'The owner is already sharing eight live viewers.' }); return () => {} }
+ const listeners = new Set([listener])
+ let stopped = false, capture: ViewerCapture | null = null, timer: NodeJS.Timeout | null = null, current: string | null = null
+ const send = (frame: Payload) => { if (!stopped) for (const receive of listeners) receive(frame) }
+ const tick = async () => {
+ try {
+ const next = viewerTarget(this.target(agentId))
+ if (next !== current) { await capture?.stop(); capture = null; current = next }
+ if (!next) send({ state: 'waiting', message: 'The viewer will appear when this harness produces an output.' })
+ else {
+ if (!capture) { send({ state: 'loading' }); capture = this.create(); await capture.start(next) }
+ if (!stopped) send({ state: 'live', mime: 'image/jpeg', data: await capture.capture(), capturedAt: Date.now() })
+ }
+ } catch (error) {
+ send({ state: 'unavailable', message: error instanceof Error ? error.message : 'The viewer is temporarily unavailable.' })
+ await capture?.stop(); capture = null
+ } finally { if (!stopped) timer = setTimeout(() => { void tick() }, capture ? 400 : 3000) }
+ }
+ this.entries.set(agentId, { listeners, stop: () => { stopped = true; if (timer) clearTimeout(timer); void capture?.stop() } })
+ void tick()
+ return () => this.remove(agentId, listener)
+ }
+ private remove(id: string, listener: Listener): void {
+ const entry = this.entries.get(id)
+ if (!entry) return
+ entry.listeners.delete(listener)
+ if (!entry.listeners.size) { entry.stop(); this.entries.delete(id) }
+ }
+ stop(): void { for (const entry of this.entries.values()) entry.stop(); this.entries.clear() }
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 2f4a7eab6..3a72146cb 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -98,15 +98,37 @@ class ApiClient {
/// The daemon answers 200 with the last known-good list when the backend leg is unreachable, so a
/// caller that only checked the status code would mistake an outage for a healthy, current read.
bool lastMachinesStale = false;
+ List<Machine> _sharedMachines = [];
Future<List<Machine>> machines() async {
final res = await _dio.get('/api/machines');
final data = unwrapApiResponse(res) as Map<String, dynamic>;
lastMachinesStale = data['stale'] == true;
final list = data['machines'] as List<dynamic>? ?? [];
- return list
+ final owned = list
.map((e) => Machine.fromJson(e as Map<String, dynamic>))
.toList();
+ try {
+ final shared = await _dio.get('/api/harness-shares');
+ if (shared.statusCode == 404) {
+ _sharedMachines = [];
+ } else {
+ final body = unwrapApiResponse(shared) as Map<String, dynamic>;
+ _sharedMachines = [
+ for (final row in body['machines'] as List? ?? const [])
+ Machine.fromJson(Map<String, dynamic>.from(row as Map)),
+ ];
+ }
+ } catch (error) {
+ if (isUnauthorizedError(error)) rethrow;
+ lastMachinesStale = true;
+ }
+ return [
+ ...owned,
+ ..._sharedMachines.where(
+ (shared) => !owned.any((own) => own.machineId == shared.machineId),
+ ),
+ ];
}
Future<String?> renameMachine({
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 14faac712..706beac84 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -62,6 +62,27 @@ class CurrentUserProfile {
}
}
+/// A view-only invitation. It never contains a full machine credential.
+class SharedHarness {
+ const SharedHarness({
+ required this.id,
+ required this.agentId,
+ required this.name,
+ this.engine,
+ required this.expiresAt,
+ });
+ final String id, agentId, name;
+ final String? engine;
+ final DateTime expiresAt;
+ factory SharedHarness.fromJson(Map<String, dynamic> j) => SharedHarness(
+ id: j['id'] as String,
+ agentId: j['agentId'] as String,
+ name: j['name'] as String,
+ engine: j['engine'] as String?,
+ expiresAt: DateTime.parse(j['expiresAt'] as String),
+ );
+}
+
/// Control-plane machine (GET /api/machines).
class Machine {
final String machineId;
@@ -73,6 +94,9 @@ class Machine {
final String? engine;
final String? name;
final String? hostname;
+ final bool isShared;
+ final String? ownerName;
+ final List<SharedHarness> sharedHarnesses;
final String? status;
const Machine({
@@ -83,6 +107,9 @@ class Machine {
this.engine,
this.name,
this.hostname,
+ this.isShared = false,
+ this.ownerName,
+ this.sharedHarnesses = const [],
this.status,
});
@@ -101,6 +128,12 @@ class Machine {
engine: j['engine'] as String?,
name: j['name'] as String?,
hostname: j['hostname'] as String?,
+ isShared: j['shared'] == true,
+ ownerName: j['ownerName'] as String?,
+ sharedHarnesses: [
+ for (final row in j['shares'] as List? ?? const [])
+ SharedHarness.fromJson(Map<String, dynamic>.from(row as Map)),
+ ],
status: j['status'] as String?,
);
@@ -112,6 +145,9 @@ class Machine {
engine: engine,
name: name ?? this.name,
hostname: hostname,
+ isShared: isShared,
+ ownerName: ownerName,
+ sharedHarnesses: sharedHarnesses,
status: status,
);
}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 814b39a64..5e2904c45 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -398,6 +398,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
(
machine.machine.machineId,
machine.machine.displayName,
+ machine.machine.isShared,
+ machine.machine.ownerName,
machine.isLocalMachine,
machine.nodeOnline,
machine.needsLink,
@@ -426,6 +428,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
'id': machine.machine.machineId,
'name': machine.machine.displayName,
'local': machine.isLocalMachine,
+ 'shared': machine.machine.isShared,
+ 'ownerName': machine.machine.ownerName,
'agentCount':
machine.agents.isNotEmpty ||
machine.agentLoadStatus == AgentLoadStatus.loaded
@@ -1508,59 +1512,59 @@ class _SwarmScreenState extends State<SwarmScreen> {
source: 'tab',
)
else
- Padding(
- padding: app.panes.isEmpty
- ? EdgeInsets.zero
- : const EdgeInsets.all(10),
- child: Focus.withExternalFocusNode(
- focusNode: _canvasFocus,
- includeSemantics: false,
- child: Stack(
- children: [
- Positioned.fill(
- child: PaneGrid(
- notifier: app,
- swarmMode: true,
- onSplit: (paneId, axis) => unawaited(
- _splitAgent(axis, paneId: paneId),
- ),
- onNewSplit: (paneId, axis) => unawaited(
- _splitAgent(
- axis,
- paneId: paneId,
- create: true,
+ Padding(
+ padding: app.panes.isEmpty
+ ? EdgeInsets.zero
+ : const EdgeInsets.all(10),
+ child: Focus.withExternalFocusNode(
+ focusNode: _canvasFocus,
+ includeSemantics: false,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: PaneGrid(
+ notifier: app,
+ swarmMode: true,
+ onSplit: (paneId, axis) => unawaited(
+ _splitAgent(axis, paneId: paneId),
+ ),
+ onNewSplit: (paneId, axis) => unawaited(
+ _splitAgent(
+ axis,
+ paneId: paneId,
+ create: true,
+ ),
),
+ empty: app.panes.isEmpty
+ ? HarnessStartPage(
+ key: ValueKey(
+ 'harness-start:${app.activeSwarmId}',
+ ),
+ focusNode: _startSearchFocus,
+ createSearch: () =>
+ SwarmSearchController(
+ app,
+ _navigation.recent,
+ projects: _projects,
+ commands: _searchCommands,
+ adding: true,
+ catalog: _searchCatalog,
+ ),
+ onNew: _newAgent,
+ onStore: app.openStore,
+ onChoose: (selection) =>
+ _activateSearch(
+ selection,
+ app.activeSwarmId,
+ ),
+ )
+ : null,
),
- empty: app.panes.isEmpty
- ? HarnessStartPage(
- key: ValueKey(
- 'harness-start:${app.activeSwarmId}',
- ),
- focusNode: _startSearchFocus,
- createSearch: () =>
- SwarmSearchController(
- app,
- _navigation.recent,
- projects: _projects,
- commands: _searchCommands,
- adding: true,
- catalog: _searchCatalog,
- ),
- onNew: _newAgent,
- onStore: app.openStore,
- onChoose: (selection) =>
- _activateSearch(
- selection,
- app.activeSwarmId,
- ),
- )
- : null,
),
- ),
- ],
+ ],
+ ),
),
),
- ),
],
),
),
@@ -1649,7 +1653,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
children: [
if (swarm.isStore)
StoreMark(
- key: ValueKey('tab-store:${swarm.id}'),
+ key: ValueKey(
+ 'tab-store:${swarm.id}',
+ ),
)
else if (_tabAgents(swarm).length == 1)
EngineMark(
diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dart
new file mode 100644
index 000000000..9149ffd3c
--- /dev/null
+++ b/desktop/lib/sharing/share_harness_dialog.dart
@@ -0,0 +1,349 @@
+import 'dart:async';
+
+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 '../state/app_state.dart';
+import '../ws/ws_conn.dart';
+
+typedef ShareAction = Future<Map<String, dynamic>> Function(
+ String action,
+ Map<String, dynamic> payload,
+);
+
+Future<void> showShareHarnessDialog(
+ BuildContext context,
+ AppNotifier app,
+ String machineId,
+ String agentId,
+ String name,
+) => showAppDialog<void>(
+ context: context,
+ builder: (_) => ShareHarnessDialog(
+ name: name,
+ manage: (action, payload) =>
+ app.manageHarnessShares(machineId, agentId, action, payload),
+ ),
+);
+
+class ShareHarnessDialog extends StatefulWidget {
+ const ShareHarnessDialog({
+ super.key,
+ required this.name,
+ required this.manage,
+ });
+ final String name;
+ final ShareAction manage;
+ @override
+ State<ShareHarnessDialog> createState() => _ShareHarnessDialogState();
+}
+
+class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
+ final _emails = TextEditingController();
+ List<Map<String, dynamic>> _shares = [];
+ bool _loading = true, _busy = false;
+ String? _error, _notice;
+ int _days = 30;
+ Timer? _presence;
+ int _revision = 0;
+ bool _refreshing = false;
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_load());
+ _presence = Timer.periodic(const Duration(seconds: 5), (_) {
+ if (!_busy) unawaited(_load(quiet: true));
+ });
+ }
+
+ @override
+ void dispose() {
+ _presence?.cancel();
+ _emails.dispose();
+ super.dispose();
+ }
+
+ String _message(Object error) =>
+ error is WsRequestFailure && error.code == 'UNSUPPORTED'
+ ? 'Update Harness on this machine to start sharing.'
+ : error is WsRequestFailure && error.detail != null
+ ? error.detail!
+ : 'Could not reach this harness. Check the connection and try again.';
+ void _accept(Map<String, dynamic> response) {
+ _shares = [
+ for (final row in response['shares'] as List? ?? const [])
+ Map<String, dynamic>.from(row as Map),
+ ];
+ }
+
+ Future<void> _load({bool quiet = false}) async {
+ if (_refreshing || _busy) return;
+ _refreshing = true;
+ final revision = _revision;
+ try {
+ final response = await widget.manage('list', const {});
+ if (mounted && revision == _revision) {
+ setState(() {
+ _accept(response);
+ _loading = false;
+ if (!quiet) _error = null;
+ });
+ }
+ } catch (error) {
+ if (mounted && !quiet && revision == _revision) {
+ setState(() {
+ _loading = false;
+ _error = _message(error);
+ });
+ }
+ } finally {
+ _refreshing = false;
+ }
+ }
+
+ Future<void> _invite() async {
+ if (_busy) return;
+ final emails = _emails.text
+ .split(RegExp(r'[,;\s]+'))
+ .where((e) => e.isNotEmpty)
+ .map((e) => e.toLowerCase())
+ .toSet()
+ .toList();
+ if (emails.isEmpty ||
+ emails.length > 20 ||
+ emails.any((e) => !RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$').hasMatch(e))) {
+ setState(() {
+ _error = 'Enter up to 20 valid email addresses, separated by commas.';
+ _notice = null;
+ });
+ return;
+ }
+ setState(() {
+ _revision++;
+ _busy = true;
+ _error = null;
+ _notice = null;
+ });
+ try {
+ final response = await widget.manage('invite', {
+ 'emails': emails,
+ 'days': _days,
+ });
+ if (mounted) {
+ setState(() {
+ _accept(response);
+ _emails.clear();
+ _notice = _shares.any((s) => s['error'] != null)
+ ? 'Some invitations could not be shared. Check the details below.'
+ : _shares.any((s) => s['pending'] == true)
+ ? 'Invitations saved. They will appear when the connection returns.'
+ : '${emails.length == 1 ? '1 person now has' : '${emails.length} people now have'} view-only access.';
+ });
+ }
+ } catch (error) {
+ if (mounted) setState(() => _error = _message(error));
+ } finally {
+ if (mounted) setState(() => _busy = false);
+ }
+ }
+
+ Future<void> _remove(String id) async {
+ if (_busy) return;
+ setState(() {
+ _revision++;
+ _busy = true;
+ _error = null;
+ _notice = null;
+ });
+ try {
+ final response = await widget.manage('remove', {'id': id});
+ if (mounted) {
+ setState(() {
+ _accept(response);
+ _notice = 'Access removed.';
+ });
+ }
+ } catch (error) {
+ if (mounted) setState(() => _error = _message(error));
+ } finally {
+ if (mounted) setState(() => _busy = false);
+ }
+ }
+
+ @override
+ Widget 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),
+ TextField(
+ controller: _emails,
+ autofocus: true,
+ enabled: !_busy && !_loading,
+ keyboardType: TextInputType.emailAddress,
+ maxLines: 2,
+ minLines: 1,
+ decoration: const InputDecoration(
+ labelText: 'Add people by email',
+ ),
+ onSubmitted: (_) => _invite(),
+ ),
+ 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);
+ },
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ FilledButton(
+ onPressed: _busy || _loading ? 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,
+ ),
+ ),
+ ),
+ ),
+ 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),
+ ),
+ ),
+ 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: const Text(
+ 'They’ll find this harness in Machines → Shared with you when they sign in with the invited email.\n\n'
+ 'Viewers can see terminal output and the viewer. Your machine needs to stay online. You can remove access at any time.',
+ style: TextStyle(fontSize: 12, 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;
+ final expires = DateTime.tryParse(share['expiresAt'] as String? ?? '');
+ final subtitle =
+ share['error'] as String? ??
+ (share['pending'] == true
+ ? 'Waiting for connection'
+ : share['expired'] == true
+ ? 'Expired · add again to renew'
+ : watching
+ ? '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: const TextStyle(fontSize: 13),
+ ),
+ ),
+ title: Text(
+ email,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 13),
+ ),
+ subtitle: Text(subtitle, style: const TextStyle(fontSize: 11)),
+ trailing: TextButton(
+ onPressed: _busy ? null : () => _remove(share['id'] as String),
+ child: const Text('Remove'),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dart
new file mode 100644
index 000000000..6744bd412
--- /dev/null
+++ b/desktop/lib/sharing/shared_harness_panel.dart
@@ -0,0 +1,322 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+
+import '../core/models.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/skeleton.dart';
+import '../state/app_state.dart';
+import '../state/terminal_pane.dart';
+import '../terminal/terminal_binary.dart';
+import '../terminal/terminal_session.dart';
+import '../widgets/terminal_panel.dart';
+import '../ws/ws_conn.dart';
+
+class SharedHarnessPanel extends StatefulWidget {
+ const SharedHarnessPanel({
+ super.key,
+ required this.notifier,
+ required this.pane,
+ required this.grant,
+ required this.hasAccess,
+ required this.visible,
+ required this.onClose,
+ });
+ final AppNotifier notifier;
+ final TerminalPane pane;
+ final SharedHarness grant;
+ final bool hasAccess, visible;
+ final VoidCallback onClose;
+ @override
+ State<SharedHarnessPanel> createState() => _SharedHarnessPanelState();
+}
+
+class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
+ late WsConn _connection;
+ late TerminalSession _terminal;
+ ConnectionStatus _status = ConnectionStatus.connecting;
+ String? _failure;
+ String _viewerMessage = 'Waiting for the live viewer…';
+ Uint8List? _image;
+ bool _viewerSelected = false, _ended = false;
+ @override
+ void initState() {
+ super.initState();
+ _start();
+ }
+
+ void _start() {
+ final uri = Uri.parse(widget.notifier.config.localCliBaseUrl)
+ .replace(scheme: 'ws', path: '/api/local-ws');
+ _terminal = TerminalSession(
+ machineId: widget.pane.machineId,
+ agentId: widget.grant.agentId,
+ agentName: widget.grant.name,
+ engineId: widget.grant.engine,
+ readOnly: true,
+ send: (type, payload) => _connection.sendTerminalFrame(type, payload),
+ sendBinary: (_) async => false,
+ onOpenStalled: () => _connection.forceReconnect(),
+ resyncTimeout: const Duration(seconds: 15),
+ );
+ _connection = WsConn(
+ wsBaseUrl: '',
+ autonomousEnv: widget.notifier.config.autonomousEnv,
+ machineId: widget.pane.machineId,
+ observerShareId: widget.grant.id,
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: uri,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: _end,
+ onLocalFailure: (code, reason) => _end(reason),
+ onEvent: (frame) async {
+ final type = frame['type'] as String,
+ payload = Map<String, dynamic>.from(frame['payload'] as Map);
+ if (type == 'observer_viewer') {
+ if (!mounted || _ended) return;
+ Uint8List? next;
+ try {
+ if (payload['data'] is String) {
+ next = base64Decode(payload['data'] as String);
+ }
+ } on FormatException {
+ return;
+ }
+ setState(() {
+ if (next != null) _image = next;
+ _viewerMessage =
+ payload['message'] as String? ??
+ (payload['state'] == 'live'
+ ? 'Live viewer'
+ : 'Opening the viewer…');
+ });
+ } else {
+ await _terminal.handleFrame(type, payload);
+ }
+ },
+ onStatus: (status) {
+ if (!mounted || _ended) return;
+ setState(() {
+ _status = status;
+ _failure = null;
+ });
+ if (status == ConnectionStatus.connected) {
+ unawaited(_terminal.reopen());
+ unawaited(
+ _connection.sendTerminalFrame('observer_viewer', {
+ 'agentId': widget.grant.agentId,
+ }),
+ );
+ } else {
+ _terminal.transportLost('Waiting for the owner to reconnect.');
+ }
+ },
+ );
+ _connection.onBinaryFrame = (bytes) async {
+ final frame = decodeTerminalLocal(bytes);
+ if (frame != null && !_ended) await _terminal.handleBinary(frame);
+ };
+ if (widget.hasAccess) {
+ unawaited(_connection.connect());
+ } else {
+ _ended = true;
+ _failure = 'Access removed or invitation expired.';
+ }
+ }
+
+ void _end(String reason) {
+ if (!mounted || _ended) return;
+ setState(() {
+ _ended = true;
+ _failure = reason;
+ _image = null;
+ });
+ _terminal.transportLost(reason);
+ unawaited(_connection.close());
+ }
+
+ @override
+ void didUpdateWidget(SharedHarnessPanel oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (!widget.hasAccess && !_ended) {
+ _end('Access removed or invitation expired.');
+ }
+ }
+
+ @override
+ void dispose() {
+ unawaited(_connection.close());
+ _terminal.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final live = !_ended && _status == ConnectionStatus.connected;
+ return Column(
+ children: [
+ Container(
+ height: 44,
+ padding: const EdgeInsets.only(left: 12, right: 4),
+ color: grid.AppSurface.recess,
+ child: Row(
+ children: [
+ const Icon(Icons.visibility_outlined, size: 16),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ widget.grant.name,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontWeight: FontWeight.w600,
+ fontSize: 13,
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ const Text('View only', style: TextStyle(fontSize: 11)),
+ 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: TextStyle(
+ fontSize: 11,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ IconButton(
+ tooltip: 'Close shared harness',
+ onPressed: widget.onClose,
+ icon: const Icon(Icons.close, size: 16),
+ ),
+ ],
+ ),
+ ),
+ if (_failure != null)
+ Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(12),
+ color: grid.AppSurface.recess,
+ child: Text(_failure!, style: const TextStyle(fontSize: 12)),
+ ),
+ 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,
+ children: [
+ if (!_ended)
+ const Skeleton(width: 220, height: 130),
+ const SizedBox(height: 14),
+ Text(
+ _viewerMessage,
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ fontSize: 12,
+ 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: [
+ Row(
+ children: [
+ TextButton(
+ onPressed: () =>
+ setState(() => _viewerSelected = false),
+ child: Text(
+ 'Terminal',
+ style: TextStyle(
+ fontWeight: !_viewerSelected
+ ? FontWeight.w600
+ : FontWeight.normal,
+ ),
+ ),
+ ),
+ TextButton(
+ onPressed: () => setState(() => _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: const TextStyle(fontSize: 11),
+ ),
+ ),
+ const SizedBox(width: 12),
+ ],
+ ),
+ Expanded(
+ child: IndexedStack(
+ index: _viewerSelected ? 1 : 0,
+ children: [terminal(), viewer()],
+ ),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 351114ecb..6bf69f226 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -291,6 +291,7 @@ class AppNotifier extends ChangeNotifier {
final AuthSession session;
AppConfig config;
late ApiClient api;
+
/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
/// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call
/// site reads the same in both.
@@ -389,6 +390,8 @@ class AppNotifier extends ChangeNotifier {
// Backend REST can fail while the daemon and its WebSocket remain ready. Recover that list
// independently, with capped backoff and the same in-flight request as a manual retry.
Timer? _machineRecoveryTimer;
+ Timer? _sharingDiscoveryTimer;
+ bool _sharingDiscoveryBusy = false;
int _machineRecoveryAttempts = 0;
String? _machineLoadError;
@@ -501,11 +504,9 @@ class AppNotifier extends ChangeNotifier {
final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;
return target == null ||
target.panes.length < maxPanes ||
- target.panes.any(
- (p) =>
- p.machineId == entry.machineId &&
- p.agentId == entry.agentId,
- );
+ target.panes.any(
+ (p) => p.machineId == entry.machineId && p.agentId == entry.agentId,
+ );
}
bool _canReopenSwarm(ClosedSwarm saved) {
@@ -2493,7 +2494,8 @@ class AppNotifier extends ChangeNotifier {
final updater = desktopUpdater ?? DesktopUpdater();
final staged = await updater.downloadAndStage(info);
if (staged == null) {
- updateError = 'Could not download and verify OpenHarness ${info.version}.';
+ updateError =
+ 'Could not download and verify OpenHarness ${info.version}.';
return false;
}
final applied = await updater.applyStaged(staged, selfPid: pid);
@@ -2778,6 +2780,21 @@ class AppNotifier extends ChangeNotifier {
/// machines", which an empty list alone cannot say.
bool machinesLoading = false;
+ Future<Map<String, dynamic>> manageHarnessShares(
+ String machineId,
+ String agentId,
+ String action, [
+ Map<String, dynamic> payload = const {},
+ ]) {
+ if (machineStates[machineId]?.machine.isShared == true) {
+ return Future.error(StateError('Only the owner can change sharing.'));
+ }
+ return _conn(machineId).request(
+ 'harness_share_$action',
+ payload: {'agentId': agentId, ...payload},
+ );
+ }
+
Future<void> refreshMachines() async {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
@@ -2966,6 +2983,31 @@ class AppNotifier extends ChangeNotifier {
(state) => state..machine = machine,
ifAbsent: () => MachineState(machine),
);
+ if (machine.isShared) {
+ state.agents = [
+ for (final grant in machine.sharedHarnesses)
+ Agent(
+ id: grant.agentId,
+ name: grant.name,
+ engine: grant.engine,
+ terminalAvailable: true,
+ ),
+ ];
+ state.agentLoadStatus = AgentLoadStatus.loaded;
+ state.needsLink = false;
+ state.nodeOnline = machine.status == 'running';
+ for (final pane in allPanes.where(
+ (p) => p.machineId == machine.machineId,
+ )) {
+ pane.sharedHarness =
+ machine.sharedHarnesses
+ .where((g) => g.agentId == pane.agentId)
+ .firstOrNull ??
+ pane.sharedHarness;
+ pane.sharedOwnerName = machine.ownerName;
+ }
+ continue;
+ }
state.localOnly =
localComputerId != null &&
_normalizeComputerId(machine.computerId) == localComputerId;
@@ -2979,6 +3021,20 @@ class AppNotifier extends ChangeNotifier {
}
if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);
_autoConnectAndLoadMachines();
+ _sharingDiscoveryTimer ??= Timer.periodic(const Duration(seconds: 15), (
+ _,
+ ) async {
+ if (_disposed ||
+ status != AppStatus.authenticated ||
+ _sharingDiscoveryBusy)
+ return;
+ _sharingDiscoveryBusy = true;
+ try {
+ await refreshMachines();
+ } finally {
+ _sharingDiscoveryBusy = false;
+ }
+ });
notifyListeners();
}
@@ -3391,6 +3447,7 @@ class AppNotifier extends ChangeNotifier {
}
void _connectMachine(MachineState machine) {
+ if (machine.machine.isShared) return;
// connFor() starts a new socket and reports `connecting` through onStatus,
// or returns the existing socket with its current status intact. Do not
// overwrite an already-connected socket when the user collapses and
@@ -3559,7 +3616,10 @@ class AppNotifier extends ChangeNotifier {
if (decision == null) return;
// The dialog may list the machines, and the person may have moved the choice.
machineId = decision.machineId;
- final error = await _startLocalModelAgent(machineId, prompt: decision.prompt);
+ final error = await _startLocalModelAgent(
+ machineId,
+ prompt: decision.prompt,
+ );
if (error != null) {
_lastError = error;
_lastErrorRetryable = false;
@@ -3591,7 +3651,10 @@ class AppNotifier extends ChangeNotifier {
/// before this dialog had buttons.
///
/// Null on success, else the sentence for the person.
- Future<String?> _startLocalModelAgent(String machineId, {String? prompt}) async {
+ Future<String?> _startLocalModelAgent(
+ String machineId, {
+ String? prompt,
+ }) async {
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
final home = await _homeFolderOf(machine);
@@ -3715,6 +3778,7 @@ class AppNotifier extends ChangeNotifier {
MachineState machine, {
bool force = false,
}) async {
+ if (machine.machine.isShared) return;
if (!_machineWorkCurrent(machine, _authRevision)) return;
if (machine.agentLoadStatus == AgentLoadStatus.loaded && !force) return;
if (machine.isLocalMachine && !machine.usesLocalTransport) {
@@ -5515,6 +5579,12 @@ class AppNotifier extends ChangeNotifier {
shared ??
TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: agentId);
final firstAgent = targetPanes.every((pane) => pane.agentId == null);
+ if (machine.machine.isShared) {
+ pane.sharedHarness = machine.machine.sharedHarnesses
+ .where((g) => g.agentId == agentId)
+ .firstOrNull;
+ pane.sharedOwnerName = machine.machine.ownerName;
+ }
targetPanes.insert(insertion.clamp(0, targetPanes.length), pane);
if (split != null) {
target.pinnedSlots.updateAll(
@@ -5586,6 +5656,14 @@ class AppNotifier extends ChangeNotifier {
if (wantedAgentId == null) return;
final machine = machineStates[pane.machineId];
if (machine == null) return;
+ if (machine.machine.isShared) {
+ pane.sharedHarness = machine.machine.sharedHarnesses
+ .where((g) => g.agentId == wantedAgentId)
+ .firstOrNull;
+ pane.sharedOwnerName = machine.machine.ownerName;
+ notifyListeners();
+ return;
+ }
if (machine.nodeOnline == false) return;
if (!machine.terminalCapabilityAvailable) return;
@@ -6682,6 +6760,7 @@ class AppNotifier extends ChangeNotifier {
_localGitProjects.dispose();
sessionPreviews.dispose();
_disposed = true;
+ _sharingDiscoveryTimer?.cancel();
_stopMachineRecovery();
if (signingIn) cliLogin.cancel();
_closedHistory.clear();
diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dart
index 54e37a404..2b2ced69d 100644
--- a/desktop/lib/state/terminal_pane.dart
+++ b/desktop/lib/state/terminal_pane.dart
@@ -1,6 +1,7 @@
import 'package:flutter/widgets.dart';
import '../terminal/terminal_session.dart';
+import '../core/models.dart' show SharedHarness;
/// What a tile shows.
///
@@ -64,6 +65,8 @@ class TerminalPane {
String? agentId;
TerminalSession? session;
+ SharedHarness? sharedHarness;
+ String? sharedOwnerName;
/// Last visible geometry, retained while this controller is parked off screen.
Size? lastViewSize;
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index 834a6d052..305c3e987 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -79,6 +79,7 @@ class TerminalSession extends ChangeNotifier {
final TerminalFrameSender send;
final TerminalBinarySender sendBinary;
final Duration resyncTimeout;
+ final bool readOnly;
/// Forces a fresh transport dial (see `WsConn.forceReconnect`) — called once when the very first
/// `terminal_open` never gets a `terminal_ready` back within [resyncTimeout]. Covers the relay
@@ -95,6 +96,7 @@ class TerminalSession extends ChangeNotifier {
required this.send,
required this.sendBinary,
this.onOpenStalled,
+ this.readOnly = false,
this.resyncTimeout = const Duration(seconds: 4),
}) {
terminal = _newTerminal();
@@ -166,7 +168,9 @@ class TerminalSession extends ChangeNotifier {
Future<void> _inputSendTail = Future<void>.value();
bool get acceptsInput =>
- status == TerminalSessionStatus.controlling && streamId != null;
+ !readOnly &&
+ status == TerminalSessionStatus.controlling &&
+ streamId != null;
/// Grok's CLI declares terminal mouse-tracking (so tmux defers wheel bytes to it, same as any
/// alt-buffer program) but doesn't correctly handle wheel reports itself — confirmed live: it
@@ -1127,6 +1131,7 @@ class TerminalSession extends ChangeNotifier {
static const _resizeCoalesceWindow = Duration(milliseconds: 50);
void resize(int width, int height) {
+ if (readOnly) return;
_pendingCols = _clampCols(width);
_pendingRows = _clampRows(height);
final last = _lastResizeFlushAt;
@@ -1241,7 +1246,7 @@ class TerminalSession extends ChangeNotifier {
}
Future<void> _sendHeartbeat() async {
- if (!acceptsInput) return;
+ if (status != TerminalSessionStatus.controlling || streamId == null) return;
final generation = _generation;
final sent = await send('terminal_alive', {'streamId': streamId});
if (!sent && _isCurrent(generation)) {
diff --git a/desktop/lib/widgets/machine_rail.dart b/desktop/lib/widgets/machine_rail.dart
index f2ede1478..8d9b3215b 100644
--- a/desktop/lib/widgets/machine_rail.dart
+++ b/desktop/lib/widgets/machine_rail.dart
@@ -693,87 +693,93 @@ class _MachineNodeState extends State<_MachineNode> {
// row. The `+` is what the rail's big Create Agent button
// used to be: that button had to guess which machine you
// meant, and this one cannot be wrong about it.
- _CaptionActions(
- shown: _hovered || _menuOpen,
- onNewAgent: () => showNewAgentDialog(
- context,
- notifier,
- machine.machineId,
- source: 'machine_row',
- ),
- menu: MenuAnchor(
- controller: _machineMenu,
- onOpen: () => setState(() => _menuOpen = true),
- onClose: () => setState(() => _menuOpen = false),
- menuChildren: [
- // Where the empty state's refresh went. It used to hang off a status line
- // that only existed while a machine had no agents, so the one machine you
- // could not reload was a machine whose list had gone stale WITH agents in
- // it. A per-machine action belongs with the machine's other ones.
- AppMenuItem(
- icon: LucideIcons.refreshCw300,
- label: 'Reload agents',
- onPressed: () {
- _machineMenu.close();
- notifier.reloadMachineData(machine.machineId);
- },
- ),
- AppMenuItem(
- icon: LucideIcons.pencil300,
- label: 'Rename Machine',
- onPressed: () {
- _machineMenu.close();
- _showRenameDialog();
- },
- ),
- if (state.isLocalMachine) ...[
- const AppMenuDivider(),
- AppMenuItem(
- icon: LucideIcons.keyRound300,
- label: 'Set remote password',
- onPressed: () {
- _machineMenu.close();
- unawaited(
- showLinkMachineDialog(context, notifier),
- );
- },
- ),
- ],
- if (!state.isLocalMachine) ...[
- const AppMenuDivider(),
+ if (!machine.isShared)
+ _CaptionActions(
+ shown: _hovered || _menuOpen,
+ onNewAgent: () => showNewAgentDialog(
+ context,
+ notifier,
+ machine.machineId,
+ source: 'machine_row',
+ ),
+ menu: MenuAnchor(
+ controller: _machineMenu,
+ onOpen: () => setState(() => _menuOpen = true),
+ onClose: () => setState(() => _menuOpen = false),
+ menuChildren: [
+ // Where the empty state's refresh went. It used to hang off a status line
+ // that only existed while a machine had no agents, so the one machine you
+ // could not reload was a machine whose list had gone stale WITH agents in
+ // it. A per-machine action belongs with the machine's other ones.
AppMenuItem(
- icon: LucideIcons.link2300,
- label: 'Remote into this machine…',
+ icon: LucideIcons.refreshCw300,
+ label: 'Reload agents',
onPressed: () {
_machineMenu.close();
- notifier.selectMachineForSetup(
+ notifier.reloadMachineData(
machine.machineId,
);
},
),
- const AppMenuDivider(),
AppMenuItem(
- icon: LucideIcons.trash2300,
- label: 'Delete machine',
- danger: true,
+ icon: LucideIcons.pencil300,
+ label: 'Rename Machine',
onPressed: () {
_machineMenu.close();
- _confirmDeleteMachine();
+ _showRenameDialog();
},
),
+ if (state.isLocalMachine) ...[
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: LucideIcons.keyRound300,
+ label: 'Set remote password',
+ onPressed: () {
+ _machineMenu.close();
+ unawaited(
+ showLinkMachineDialog(
+ context,
+ notifier,
+ ),
+ );
+ },
+ ),
+ ],
+ if (!state.isLocalMachine) ...[
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: LucideIcons.link2300,
+ label: 'Remote into this machine…',
+ onPressed: () {
+ _machineMenu.close();
+ notifier.selectMachineForSetup(
+ machine.machineId,
+ );
+ },
+ ),
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: LucideIcons.trash2300,
+ label: 'Delete machine',
+ danger: true,
+ onPressed: () {
+ _machineMenu.close();
+ _confirmDeleteMachine();
+ },
+ ),
+ ],
],
- ],
- builder: (context, controller, child) =>
- AppIconButton(
- icon: LucideIcons.ellipsis300,
- size: 16,
- tooltip: 'Machine options',
- onPressed: () => controller.isOpen
- ? controller.close()
- : controller.open(),
- ),
+ builder: (context, controller, child) =>
+ AppIconButton(
+ icon: LucideIcons.ellipsis300,
+ size: 16,
+ tooltip: 'Machine options',
+ onPressed: () => controller.isOpen
+ ? controller.close()
+ : controller.open(),
+ ),
+ ),
),
- ),
],
),
),
@@ -1118,7 +1124,9 @@ class _AgentRowState extends State<_AgentRow> {
},
// The same "Edit name" the row's own menu opens — a double click is
// just the shorter way to it, and the place a hand reaches first.
- onDoubleTap: _showRenameDialog,
+ onDoubleTap: notifier.stateOf(machineId)?.machine.isShared == true
+ ? null
+ : _showRenameDialog,
// No tooltip on a row that works. "Claude engine" only repeated what
// the mark beside it already says, and it followed the pointer down
@@ -1188,46 +1196,49 @@ class _AgentRowState extends State<_AgentRow> {
// its own menu is open, where a button that vanished under the menu
// it opened would leave the panel pointing at nothing.
trailingAlwaysVisible: _menuOpen,
- trailing: MenuAnchor(
- controller: _agentMenu,
- onOpen: () => setState(() => _menuOpen = true),
- onClose: () => setState(() => _menuOpen = false),
- menuChildren: [
- AppMenuItem(
- icon: LucideIcons.pencil300,
- label: 'Edit name',
- onPressed: () {
- _agentMenu.close();
- _showRenameDialog();
- },
- ),
- const AppMenuDivider(),
- AppMenuItem(
- icon: LucideIcons.refreshCw300,
- label: 'Restart Harness',
- onPressed: () {
- _agentMenu.close();
- _restartAgent();
- },
- ),
- const AppMenuDivider(),
- AppMenuItem(
- icon: Icons.stop_rounded,
- label: 'Stop Harness',
- danger: true,
- onPressed: () {
- _agentMenu.close();
- _confirmDelete();
- },
- ),
- ],
- builder: (context, controller, child) => AppIconButton(
- icon: LucideIcons.ellipsis300,
- size: 16,
- onPressed: () =>
- controller.isOpen ? controller.close() : controller.open(),
- ),
- ),
+ trailing: notifier.stateOf(machineId)?.machine.isShared == true
+ ? const Icon(Icons.visibility_outlined, size: 14)
+ : MenuAnchor(
+ controller: _agentMenu,
+ onOpen: () => setState(() => _menuOpen = true),
+ onClose: () => setState(() => _menuOpen = false),
+ menuChildren: [
+ AppMenuItem(
+ icon: LucideIcons.pencil300,
+ label: 'Edit name',
+ onPressed: () {
+ _agentMenu.close();
+ _showRenameDialog();
+ },
+ ),
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: LucideIcons.refreshCw300,
+ label: 'Restart Harness',
+ onPressed: () {
+ _agentMenu.close();
+ _restartAgent();
+ },
+ ),
+ const AppMenuDivider(),
+ AppMenuItem(
+ icon: Icons.stop_rounded,
+ label: 'Stop Harness',
+ danger: true,
+ onPressed: () {
+ _agentMenu.close();
+ _confirmDelete();
+ },
+ ),
+ ],
+ builder: (context, controller, child) => AppIconButton(
+ icon: LucideIcons.ellipsis300,
+ size: 16,
+ onPressed: () => controller.isOpen
+ ? controller.close()
+ : controller.open(),
+ ),
+ ),
),
),
),
diff --git a/desktop/lib/widgets/machines_manager.dart b/desktop/lib/widgets/machines_manager.dart
index 5bba61b46..05fafa36d 100644
--- a/desktop/lib/widgets/machines_manager.dart
+++ b/desktop/lib/widgets/machines_manager.dart
@@ -95,15 +95,17 @@ class _MachinesManagerState extends State<_MachinesManager> {
if (machines[i].needsLink) 'Link required',
].join(' · '),
),
- trailing: TextButton(
- onPressed: () => showMachineRenameDialog(
- context,
- widget.notifier,
- machines[i].machine.machineId,
- machines[i].machine.displayName,
- ),
- child: const Text('Rename'),
- ),
+ trailing: machines[i].machine.isShared
+ ? const Text('View only')
+ : TextButton(
+ onPressed: () => showMachineRenameDialog(
+ context,
+ widget.notifier,
+ machines[i].machine.machineId,
+ machines[i].machine.displayName,
+ ),
+ child: const Text('Rename'),
+ ),
),
],
],
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index ab8ac0a32..7a0b561a4 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -64,6 +64,15 @@ Future<NewAgentDialogResult?> showNewAgentDialog(
// Reported here rather than at each call site: the doors are four and
// growing, and one that forgets to track is a hole in the funnel that only
// shows up as a number quietly being too small.
+ if (notifier.stateOf(machineId)?.machine.isShared == true) {
+ machineId =
+ notifier.machineStates.values
+ .where((m) => !m.machine.isShared)
+ .firstOrNull
+ ?.machine
+ .machineId ??
+ '';
+ }
analytics.newAgentOpened(source: source);
return showAppDialog<NewAgentDialogResult>(
context: context,
@@ -1245,7 +1254,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
(machine.nodeOnline == true && !machine.needsLink);
List<MachineState> get _orderedMachines {
- final machines = widget.notifier.machineStates.values.toList();
+ final machines = widget.notifier.machineStates.values
+ .where((m) => !m.machine.isShared)
+ .toList();
int priority(MachineState machine) => machine.isLocalMachine
? 0
: _machineOnline(machine)
@@ -1282,23 +1293,24 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
.toList(),
options: [
for (final machine in widget.notifier.machineStates.values)
- SelectOption(
- value: machine.machine.machineId,
- label: machine.machine.displayName,
- detail: machine.isLocalMachine ? 'This computer' : 'Remote',
- leading: () => Icon(
- _machineOnline(machine)
- ? (machine.isLocalMachine
- ? LucideIcons.laptop
- : LucideIcons.monitor)
- : LucideIcons.monitorOff,
- size: 22,
- color: _machineOnline(machine)
- ? grid.AppPalette.textPrimary
- : grid.AppPalette.textFaint,
- semanticLabel: _machineOnline(machine) ? 'Online' : 'Offline',
+ if (!machine.machine.isShared)
+ SelectOption(
+ value: machine.machine.machineId,
+ label: machine.machine.displayName,
+ detail: machine.isLocalMachine ? 'This computer' : 'Remote',
+ leading: () => Icon(
+ _machineOnline(machine)
+ ? (machine.isLocalMachine
+ ? LucideIcons.laptop
+ : LucideIcons.monitor)
+ : LucideIcons.monitorOff,
+ size: 22,
+ color: _machineOnline(machine)
+ ? grid.AppPalette.textPrimary
+ : grid.AppPalette.textFaint,
+ semanticLabel: _machineOnline(machine) ? 'Online' : 'Offline',
+ ),
),
- ),
],
onChanged: (id) {
if (id == _machineId || _choicesLocked) return;
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 8dad902df..0359ae39f 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1,3 +1,5 @@
+import '../sharing/shared_harness_panel.dart';
+
import 'dart:typed_data';
import 'package:desktop_drop/desktop_drop.dart';
@@ -1266,6 +1268,20 @@ class _PaneContent extends StatelessWidget {
Widget build(BuildContext context) {
final machine = notifier.stateOf(pane.machineId);
void close() => notifier.closePane(pane.id);
+ if (pane.sharedHarness case final grant?) {
+ return SharedHarnessPanel(
+ key: ValueKey('shared-pane-${pane.id}'),
+ notifier: notifier,
+ pane: pane,
+ grant: grant,
+ visible: visible,
+ onClose: close,
+ hasAccess:
+ machine?.machine.sharedHarnesses.any((s) => s.id == grant.id) ==
+ true,
+ );
+ }
+
// A harness's viewer: the one tile that is not a terminal and not about a
// machine. Decided first, before anything below reads `agentId` — which a
// viewer keeps null on purpose (see TerminalPane.ownerAgentId).
@@ -2176,8 +2192,11 @@ String viewerPaneName(Agent? owner, Iterable<DshEntry> catalog) {
final used = entry?.viewerUse;
if (used != null) {
final viewer = catalog.where((e) => e.id == used).firstOrNull;
- if (viewer != null && viewer.name.trim().isNotEmpty) return viewer.name.trim();
+ if (viewer != null && viewer.name.trim().isNotEmpty)
+ return viewer.name.trim();
}
final harness = owner.dshName ?? entry?.name;
- return harness == null || harness.trim().isEmpty ? 'Viewer' : '${harness.trim()} Viewer';
+ return harness == null || harness.trim().isEmpty
+ ? 'Viewer'
+ : '${harness.trim()} Viewer';
}
diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dart
index 25e80f425..93253249c 100644
--- a/desktop/lib/widgets/pane_header_actions.dart
+++ b/desktop/lib/widgets/pane_header_actions.dart
@@ -11,6 +11,7 @@ class PaneHeaderActions extends StatelessWidget {
required this.zoomed,
this.onZoom,
this.onRestart,
+ this.onShare,
this.onDelete,
this.onClose,
this.onToggleComposer,
@@ -23,6 +24,7 @@ class PaneHeaderActions extends StatelessWidget {
});
final bool zoomed, composerVisible;
+ final VoidCallback? onShare;
final VoidCallback? onZoom, onRestart, onDelete, onClose, onToggleComposer;
/// A harness agent's viewer: show it beside this terminal, or hide it.
@@ -90,6 +92,10 @@ class PaneHeaderActions extends StatelessWidget {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
+ if (onShare != null) ...[
+ action('Share harness', Icons.person_add_alt_1_outlined, onShare),
+ const SizedBox(width: 2),
+ ],
if (modelPicker != null) ...[
modelPicker!,
const SizedBox(width: 4),
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 021f43c7e..5f7819666 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -1,3 +1,5 @@
+import '../sharing/share_harness_dialog.dart';
+
import 'dart:async';
import 'dart:math' as math;
@@ -1254,7 +1256,7 @@ class _TerminalPanelState extends State<TerminalPanel>
session.terminal,
key: _terminalViewKey,
controller: _controller,
- autoResize: widget.visible,
+ autoResize: widget.visible && !session.readOnly,
resizeBuffer: false,
renderingEnabled: widget.visible,
scrollController: _scrollController,
@@ -1722,6 +1724,21 @@ class _TerminalHeader extends StatelessWidget {
),
)
: null,
+ onShare:
+ readOnly ||
+ notifier
+ .stateOf(session.machineId)
+ ?.machine
+ .isShared ==
+ true
+ ? null
+ : () => showShareHarnessDialog(
+ context,
+ notifier,
+ session.machineId,
+ session.agentId,
+ session.agentName,
+ ),
zoomed: zoomed,
onZoom: onToggleZoom,
onRestart: onRestart,
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index e50c5b779..1ce65bd9c 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -79,6 +79,7 @@ class WsConn {
/// Retained only for fixture constructor compatibility. Local transport ignores it.
final String? localApiKey;
+ final String? observerShareId;
final int localProtocolVersion;
/// A viewer build's end-to-end session with the machine, minted fresh on every connect — the
@@ -169,6 +170,7 @@ class WsConn {
this.transportKind = WsTransportKind.cloudE2ee,
this.localWsUri,
this.localApiKey,
+ this.observerShareId,
this.localProtocolVersion = 1,
this.relayCodecs,
this.transportPlugins,
@@ -241,6 +243,7 @@ class WsConn {
'type': 'machine_select',
'payload': {
'machineId': machineId,
+ if (observerShareId != null) 'shareId': observerShareId,
if (isLocal) 'localProtocolVersion': localProtocolVersion,
if (isLocal && forceRelayReconnect) 'forceReconnect': true,
},
@@ -679,7 +682,7 @@ class WsConn {
}
final code = channel.closeCode;
if (isLocal) {
- if (code == 4404) {
+ if (code == 4404 || (observerShareId != null && code == 4403)) {
_closing = true;
// needsLink first: AppNotifier's onStatus handler reads machine.needsLink
// to decide whether a disconnect should be treated as the node going
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 300603350..38682a114 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -319,7 +319,15 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
manager.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "manageMachines")
machinesMenu.addItem(manager)
machinesMenu.addItem(.separator())
- for (machine, parts) in zip(machines, labels) {
+ var lastSection: Bool? = nil
+ for (machine, parts) in zip(machines, labels).sorted(by: { !$0.0.shared && $1.0.shared }) {
+ if lastSection != machine.shared {
+ if lastSection != nil { machinesMenu.addItem(.separator()) }
+ let header = NSMenuItem(title: machine.shared ? "Shared with you" : "Your machines", action: nil, keyEquivalent: "")
+ header.isEnabled = false
+ machinesMenu.addItem(header)
+ lastSection = machine.shared
+ }
let item = NSMenuItem(title: machine.name, action: #selector(machineAction(_:)), keyEquivalent: "")
item.target = self
item.representedObject = machine.id
@@ -331,16 +339,17 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
// right): the agent count, or the link/offline status when there is no
// count. The two are independent slots, so a machine can read
// "Online … Link required".
- let afterName = parts.presence.isEmpty ? "" : " " + parts.presence
+ let owner = machine.shared && !machine.ownerName.isEmpty ? " · " + machine.ownerName : ""
+ let afterName = owner + (parts.presence.isEmpty ? "" : " " + parts.presence)
let trailing = parts.count.isEmpty ? parts.status : parts.count
label.append(NSAttributedString(string: afterName + "\t" + trailing,
attributes: [.font: NSFont.menuFont(ofSize: 0), .paragraphStyle: paragraph,
.foregroundColor: NSColor.secondaryLabelColor]))
item.attributedTitle = label
- item.image = NSImage(systemSymbolName: machine.local ? "laptopcomputer" : "desktopcomputer", accessibilityDescription: nil)
+ item.image = NSImage(systemSymbolName: machine.shared ? "person.2" : machine.local ? "laptopcomputer" : "desktopcomputer", accessibilityDescription: machine.shared ? "Shared machine" : nil)
let submenu = NSMenu(title: machine.name)
for agent in machine.agents {
- let child = NSMenuItem(title: agent.title, action: #selector(machineAgentAction(_:)), keyEquivalent: "")
+ let child = NSMenuItem(title: agent.title + (machine.shared ? " · View only" : ""), action: #selector(machineAgentAction(_:)), keyEquivalent: "")
child.target = self
child.representedObject = ["machineId": machine.id, "agentId": agent.id]
child.image = historyIcons.image(engine: agent.engine, asset: agent.iconAsset)
@@ -364,6 +373,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
empty.isEnabled = false
submenu.addItem(empty)
}
+ if !machine.shared {
submenu.addItem(.separator())
let find = NSMenuItem(title: "Find Harnesses…", action: #selector(machineAction(_:)), keyEquivalent: "")
find.target = self
@@ -377,6 +387,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
del.image = NSImage(systemSymbolName: "trash", accessibilityDescription: nil)
submenu.addItem(del)
}
+ }
item.submenu = submenu
machinesMenu.addItem(item)
}
@@ -696,6 +707,8 @@ private struct SwarmMachineEntry: Equatable {
let local: Bool
let agentCount: Int?
let agents: [SwarmMachineAgent]
+ let shared: Bool
+ let ownerName: String
init?(_ row: [String: Any]) {
guard let id = row["id"] as? String, !id.isEmpty,
let name = row["name"] as? String, !name.isEmpty else { return nil }
@@ -704,6 +717,8 @@ private struct SwarmMachineEntry: Equatable {
status = String((row["status"] as? String ?? "").prefix(80))
presence = String((row["presence"] as? String ?? "").prefix(80))
linkRequired = row["linkRequired"] as? Bool == true
+ shared = row["shared"] as? Bool == true
+ ownerName = String((row["ownerName"] as? String ?? "").prefix(100))
local = row["local"] as? Bool == true
agentCount = (row["agentCount"] as? Int).map { max(0, $0) }
agents = (row["agents"] as? [[String: Any]] ?? []).prefix(512).compactMap(SwarmMachineAgent.init)