The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Cover sharing lifecycle and enforce view-only desktop behavior
Dee44d44f25c1bb
diff --git a/backend/src/lib/observerWs.test.ts b/backend/src/lib/observerWs.test.tsindex 9c7d91c34..a9fa9f35c 100644--- a/backend/src/lib/observerWs.test.ts+++ b/backend/src/lib/observerWs.test.ts@@ -129,4 +129,28 @@ describe('isolated observer WebSocket boundary', () => {handleObserverUpgrade(req(`/api/observer-ws?share=${share.id}`) as never, socket as never, Buffer.alloc(0)); await flush()expect(m.upgrade).toHaveBeenCalledTimes(2)})+ it('cleans up upgrade failures, synchronous relay faults, closed inboxes and excessive queued messages', async () => {+ const socket = { destroyed: false, destroy: vi.fn() }+ handleObserverUpgrade({ headers: { 'sec-websocket-protocol': 'fixture' } } as never, socket as never, Buffer.alloc(0))+ await flush(); expect(socket.destroy).toHaveBeenCalledTimes(1)+ const req = { url: `/api/observer-ws?share=${share.id}`, headers: { 'sec-websocket-protocol': 'fixture' } }+ m.changed.mockRejectedValueOnce(new Error('subscription down'))+ handleObserverUpgrade(req as never, socket as never, Buffer.alloc(0)); await flush()+ expect(ws.close).toHaveBeenCalledWith(1013, 'Sharing temporarily unavailable')+ socket.destroyed = true; m.auth.mockRejectedValueOnce(new Error('auth down'))+ handleObserverUpgrade(req as never, socket as never, Buffer.alloc(0)); await flush()+ expect(socket.destroy).toHaveBeenCalledTimes(1)+ ws = new Socket(); await attach()+ m.down.mockImplementationOnce(() => { throw new Error('relay not initialized') })+ hello(); await flush()+ expect(ws.close).toHaveBeenCalledWith(1013, 'Sharing temporarily unavailable')+ ws = new Socket(); await attach()+ let release!: () => void+ m.down.mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(1) }))+ hello(); await flush()+ m.down.mockRejectedValueOnce(new Error('cleanup relay down'))+ for (let i = 0; i < 257; i++) ws.message('observer_frame', { __e2e: {} })+ expect(ws.close).toHaveBeenCalledWith(1008, 'Too many observer messages')+ release(); await flush(); await vi.advanceTimersByTimeAsync(1)+ })})diff --git a/backend/src/lib/observerWs.ts b/backend/src/lib/observerWs.tsindex 2321cd284..8b54698c1 100644--- a/backend/src/lib/observerWs.ts+++ b/backend/src/lib/observerWs.ts@@ -39,7 +39,6 @@ export async function attachObserver(ws: WebSocket, user: AuthUser, share: NonNulet opened = falseconst down = (type: string, payload: unknown) => publishDown(share.machineId, { connId, frame: { type, payload } })const close = () => {- if (closed) returnclosed = truefor (const dispose of disposers.splice(0)) dispose()void down('observer_close', {}).catch(() => {})diff --git a/cli/scripts/share-harness-e2e.ts b/cli/scripts/share-harness-e2e.tsindex f6fd193fe..2a60436d6 100644--- a/cli/scripts/share-harness-e2e.ts+++ b/cli/scripts/share-harness-e2e.ts@@ -70,7 +70,7 @@ class Peer {if (!frame) returnthis.binary.push(frame)this.text += (frame.compressed ? inflateSync(frame.bytes) : Buffer.from(frame.bytes)).toString()- this.send('terminal_ack', { streamId: frame.streamId, seq: frame.seq })+ this.send('terminal_ack', { streamId: frame.streamId, lastSeq: frame.seq })} else {const frame = JSON.parse(raw.toString()); this.frames.push(frame)if (frame.type === 'terminal_ready') { this.stream = frame.payload.streamId; this.inputSequence = 0 }diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex 8a5bb404e..ee124b203 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -67,6 +67,7 @@ describe('TerminalBackendCoordinator', () => {{ engine: 'claude', processIdentity: current.processIdentity },{ cols: 80, rows: 24 },sink,+ false,)})diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex 7a5684706..c40311652 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -189,7 +189,7 @@ export class TerminalBackendCoordinator {session: RegisteredSession,size: TerminalStreamSize,sink: TerminalStreamSink,- readOnly?: boolean,+ readOnly = false,): Promise<TerminalReadResult<TerminalStreamHandle>> {// `active` describes whether the engine process was discovered, not whether the retained// terminal runtime is still viewable. A dormant agent can legitimately be waiting at setup,diff --git a/cli/src/sharing/owner.spec.ts b/cli/src/sharing/owner.spec.tsindex 929f6fd29..4191915ba 100644--- a/cli/src/sharing/owner.spec.ts+++ b/cli/src/sharing/owner.spec.ts@@ -221,4 +221,24 @@ describe('owner authority and read-only observation', () => {expect(frames.at(-1)?.payload).toMatchObject({ reason: 'Owner disconnected', retry: true })owner.close('observer:already-gone')})+ it('keeps valid observers alive, retries on its clock and recovers from a local persistence error', async () => {+ await invite(['[email protected]', '[email protected]'])+ const ken = await connect(); await connect('[email protected]', 'observer:diego')+ await vi.advanceTimersByTimeAsync(30000)+ expect(frames.filter(f => f.type === 'observer_closed')).toHaveLength(0)+ await owner.manage('harness_share_remove', { agentId: 'agent', id: ken.grant.id })+ expect((await owner.manage('harness_share_list', { agentId: 'agent' })).shares).toEqual([expect.objectContaining({ watching: 1 })])+ vi.spyOn(store, 'invite').mockImplementationOnce(() => { throw new Error('Disk full') })+ await expect(invite()).rejects.toThrow('Disk full')+ expect((await owner.manage('harness_share_list', { agentId: 'agent' })).shares).toHaveLength(1)+ const other = store.all().find(g => g.recipientEmail === '[email protected]')!+ store.failed(other.id, 'not published')+ expect(store.all().find(g => g.id === ken.grant.id)?.publicationError).toBeNull()+ store.invite(other)+ let finish!: (result: { status: number; body: {} }) => void+ publish.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))+ const sync = owner.sync()+ store.revoke(other.id, 'machine', 'agent'); finish({ status: 403, body: {} }); await sync+ expect(store.all().find(g => g.id === other.id)).toMatchObject({ revoked: true, publicationError: null, pending: true })+ })})diff --git a/cli/src/sharing/relay.spec.ts b/cli/src/sharing/relay.spec.tsindex d68485f6b..057d2415b 100644--- a/cli/src/sharing/relay.spec.ts+++ b/cli/src/sharing/relay.spec.ts@@ -60,6 +60,8 @@ describe('recipient relay', () => {expect(sink.sendBinary).toHaveBeenCalledWith(Buffer.from('output'))frame(ws, 'observer_frame', owner.cipher.seal({ type: 'observer_viewer', payload: { state: 'live', data: 'pixels' } }))expect(sink.sendFrame).toHaveBeenCalledWith({ type: 'observer_viewer', payload: { state: 'live', data: 'pixels' } })+ frame(ws, 'unrelated_broadcast')+ ws.emit('error', new Error('socket closing'))frame(ws, 'observer_frame', owner.cipher.seal({ type: 'observer_binary', payload: { bytes: 5 } }))expect(sink.sendBinary).toHaveBeenCalledTimes(1)await session.sendBinary({} as never)diff --git a/cli/src/sharing/relay.ts b/cli/src/sharing/relay.tsindex dcbd8c611..cdff5e2fb 100644--- a/cli/src/sharing/relay.ts+++ b/cli/src/sharing/relay.ts@@ -38,7 +38,6 @@ export class HarnessShareRelay {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) returnsettled = true; clearTimeout(timeout)sink.sendFrame({ type: 'connected', payload: { machineId, e2ee: false, readOnly: true } })resolve()diff --git a/cli/src/sharing/viewer.spec.ts b/cli/src/sharing/viewer.spec.tsnew file mode 100644index 000000000..5b3a092b0--- /dev/null+++ b/cli/src/sharing/viewer.spec.ts@@ -0,0 +1,194 @@+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'+const m = vi.hoisted(() => ({ spawn: vi.fn(), exists: vi.fn(), directory: vi.fn(), rm: vi.fn(), sockets: [] as any[], reply: vi.fn() }))+vi.mock('node:child_process', () => ({ spawn: m.spawn }))+vi.mock('node:fs', async actual => ({ ...await actual<typeof import('node:fs')>(), existsSync: m.exists }))+vi.mock('node:fs/promises', () => ({ mkdtemp: m.directory, rm: m.rm }))+vi.mock('ws', async () => {+ const { EventEmitter } = await import('node:events')+ class Socket extends EventEmitter {+ static OPEN = 1+ readyState = 1+ send = vi.fn((raw: string) => {+ const request = JSON.parse(raw), response = m.reply(request)+ if (response !== undefined) queueMicrotask(() => this.emit('message', Buffer.from(JSON.stringify({ id: request.id, ...response }))))+ })+ terminate = vi.fn(() => this.emit('close'))+ constructor(..._args: unknown[]) { super(); m.sockets.push(this); queueMicrotask(() => this.emit('open')) }+ }+ return { WebSocket: Socket }+})+import { EventEmitter } from 'node:events'+import { ViewerCapture, SharedViewerPool, viewerTarget, viewerBrowser } from './viewer.js'+class Child extends EventEmitter {+ stderr = new EventEmitter(); exitCode: number | null = null; signalCode: string | null = null+ kill = vi.fn((signal: string) => { this.signalCode = signal; queueMicrotask(() => this.emit('exit')); return true })+}+const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve() }+describe('private viewer capture', () => {+ let capture: ViewerCapture, child: Child+ beforeEach(() => {+ vi.useFakeTimers(); vi.clearAllMocks(); m.sockets = []+ m.exists.mockReturnValue(true); m.directory.mockResolvedValue('/tmp/share-viewer-fixture'); m.rm.mockResolvedValue(undefined)+ child = new Child(); m.spawn.mockImplementation(() => {+ queueMicrotask(() => child.stderr.emit('data', Buffer.from('DevTools listening on ws://127.0.0.1:1234/devtools/browser/test\n')))+ return child+ })+ m.reply.mockImplementation(({ method }) => ({ result: method === 'Target.createTarget' ? { targetId: 'page' }+ : method === 'Target.attachToTarget' ? { sessionId: 'session' }+ : method === 'Page.captureScreenshot' ? { data: 'jpeg' } : {} }))+ capture = new ViewerCapture()+ })+ afterEach(async () => { await capture.stop(); vi.useRealTimers(); vi.unstubAllEnvs() })+ it('accepts only explicit loopback viewer URLs without credentials', () => {+ for (const url of ['http://127.0.0.1:1234/', 'http://localhost:1234/result', 'http://[::1]:1234/']) expect(viewerTarget(url)).toBe(url)+ for (const url of [null, '', 'bad', 'file:///tmp/result', 'https://127.0.0.1:1234', 'http://example.com:1234',+ 'http://localhost/', 'http://user:password@localhost:1234/', 'http://127.0.0.1.evil:1234']) expect(viewerTarget(url)).toBeNull()+ vi.stubEnv('HARNESS_VIEWER_BROWSER', '/custom/browser'); expect(viewerBrowser()).toBe('/custom/browser')+ m.exists.mockReturnValue(false); expect(viewerBrowser()).toBeNull()+ })+ it('launches an isolated, credential-free renderer and sends only constrained screenshot commands', async () => {+ await capture.start('http://localhost:1234/')+ expect(m.spawn.mock.calls[0][1]).toEqual(expect.arrayContaining(['--headless=new', '--disable-sync', '--disable-extensions', '--remote-debugging-address=127.0.0.1', '--user-data-dir=/tmp/share-viewer-fixture']))+ expect(await capture.capture()).toBe('jpeg')+ const requests = m.sockets[0].send.mock.calls.map((args: any[]) => JSON.parse(args[0]))+ expect(requests.find((r: any) => r.method === 'Page.navigate')).toMatchObject({ sessionId: 'session', params: { url: 'http://localhost:1234/' } })+ expect(requests.some((r: any) => r.method.startsWith('Input.'))).toBe(false)+ m.sockets[0].emit('message', Buffer.from('bad JSON')); m.sockets[0].emit('message', Buffer.from('{}'))+ await capture.stop()+ expect(child.kill).toHaveBeenCalledWith('SIGTERM'); expect(m.rm).toHaveBeenCalledWith('/tmp/share-viewer-fixture', { recursive: true, force: true })+ await expect(capture.capture()).rejects.toThrow('disconnected')+ })+ it('handles unavailable browsers, invalid targets, navigation failures and invalid screenshots', async () => {+ await expect(capture.start('file:///tmp/x')).rejects.toThrow('no live viewer')+ m.exists.mockReturnValue(false)+ await expect(capture.start('http://localhost:1234')).rejects.toThrow('Chrome')+ m.exists.mockReturnValue(true)+ m.reply.mockImplementation(({ method }) => ({ result: method === 'Page.navigate' ? { errorText: 'not found' } : {} }))+ await expect(capture.start('http://localhost:1234')).rejects.toThrow('not answering')+ for (const data of [undefined, 'x'.repeat(2 * 1024 * 1024 + 1)]) {+ m.reply.mockReturnValue({ result: { data } }); await expect(capture.capture()).rejects.toThrow('too large')+ }+ m.reply.mockReturnValue({ error: { message: 'render error' } })+ await expect(capture.capture()).rejects.toThrow('render this frame')+ m.reply.mockReturnValue({})+ await expect(capture.capture()).rejects.toThrow('too large')+ })+ it('bounds startup and capture time and rejects pending work on disconnect', async () => {+ m.spawn.mockReturnValue(child)+ const startup = capture.start('http://localhost:1234'); const slow = expect(startup).rejects.toThrow('too long to start')+ await vi.advanceTimersByTimeAsync(15000); await slow+ await capture.stop(); capture = new ViewerCapture(); child = new Child()+ m.spawn.mockImplementation(() => { queueMicrotask(() => child.stderr.emit('data', Buffer.from('DevTools listening on ws://localhost:1234/test'))); return child })+ await capture.start('http://localhost:1234')+ m.reply.mockReturnValue(undefined)+ const frame = capture.capture(); const timeout = expect(frame).rejects.toThrow('too long to respond')+ await vi.advanceTimersByTimeAsync(8000); await timeout+ const pending = capture.capture(); const disconnected = expect(pending).rejects.toThrow('disconnected')+ m.sockets.at(-1).emit('error', new Error('gone')); await disconnected+ })+ it('handles process startup errors and exits and cancellation before allocating a renderer', async () => {+ m.spawn.mockReturnValue(child)+ const startup = capture.start('http://localhost:1234'), failure = expect(startup).rejects.toThrow('could not start')+ await flush(); child.emit('error', new Error('ENOENT')); await failure+ await capture.stop(); capture = new ViewerCapture(); child = new Child(); m.spawn.mockReturnValue(child)+ const again = capture.start('http://localhost:1234'), exit = expect(again).rejects.toThrow('stopped')+ await flush(); child.emit('exit'); await exit+ await capture.stop(); capture = new ViewerCapture(); await capture.stop()+ const count = m.spawn.mock.calls.length+ await capture.start('http://localhost:1234')+ expect(m.spawn).toHaveBeenCalledTimes(count)+ })+ it('force-stops a hung renderer and tolerates already-deleted temporary files', async () => {+ await capture.start('http://localhost:1234')+ child.kill.mockReturnValue(true); m.rm.mockRejectedValue(new Error('already removed'))+ const stopped = capture.stop(); await vi.advanceTimersByTimeAsync(3000); await stopped+ expect(child.kill).toHaveBeenCalledWith('SIGKILL')+ })+ it('handles partial browser diagnostics and cancellation immediately after its endpoint appears', async () => {+ m.spawn.mockReturnValue(child)+ const startup = capture.start('http://localhost:1234'); await flush()+ child.stderr.emit('data', Buffer.from('browser startup diagnostics\n'))+ child.stderr.emit('data', Buffer.from('DevTools listening on ws://localhost:1234/test\n'))+ const stopping = capture.stop()+ await startup; await stopping+ expect(m.sockets).toHaveLength(0)+ })+})++describe('viewer sharing pool', () => {+ let pool: SharedViewerPool, target: string | null, create: ReturnType<typeof vi.fn<() => ViewerCapture>>, renderers: Array<{ start: any; capture: any; stop: any }>+ beforeEach(() => {+ vi.useFakeTimers(); target = null; renderers = []+ create = vi.fn(() => {+ const renderer = { start: vi.fn(async () => {}), capture: vi.fn(async () => 'jpeg'), stop: vi.fn(async () => {}) }+ renderers.push(renderer); return renderer as unknown as ViewerCapture+ })+ pool = new SharedViewerPool(() => target, () => create() as ViewerCapture)+ })+ afterEach(() => { pool.stop(); vi.useRealTimers() })+ it('waits for output, shares one camera between recipients, updates targets and releases the last watcher', async () => {+ const ken = vi.fn(), diego = vi.fn()+ const leaveKen = pool.watch('agent', ken), leaveDiego = pool.watch('agent', diego)+ await flush(); expect(ken).toHaveBeenCalledWith(expect.objectContaining({ state: 'waiting' })); expect(create).not.toHaveBeenCalled()+ target = 'http://localhost:1234'; await vi.advanceTimersByTimeAsync(3000)+ expect(create).toHaveBeenCalledTimes(1)+ expect(ken).toHaveBeenCalledWith(expect.objectContaining({ state: 'live', data: 'jpeg' }))+ expect(diego).toHaveBeenCalledWith(expect.objectContaining({ state: 'live' }))+ leaveKen(); await vi.advanceTimersByTimeAsync(400)+ expect(renderers[0].stop).not.toHaveBeenCalled()+ target = 'http://localhost:2345'; await vi.advanceTimersByTimeAsync(400)+ expect(renderers[0].stop).toHaveBeenCalled(); expect(create).toHaveBeenCalledTimes(2)+ leaveDiego(); leaveDiego(); await flush()+ expect(renderers[1].stop).toHaveBeenCalledTimes(1)+ })+ it('limits cameras and retries startup failures without exposing an HTTP proxy', async () => {+ target = 'http://localhost:1234'+ for (let i = 0; i < 8; i++) pool.watch(`agent-${i}`, vi.fn())+ const refused = vi.fn(); pool.watch('too-many', refused)()+ expect(refused).toHaveBeenCalledWith(expect.objectContaining({ state: 'unavailable' }))+ await flush(); pool.stop()+ const callback = vi.fn()+ pool.watch('retry', callback); await flush()+ renderers.at(-1)!.capture.mockRejectedValueOnce(new Error('viewer asleep'))+ await vi.advanceTimersByTimeAsync(400)+ expect(callback).toHaveBeenCalledWith({ state: 'unavailable', message: 'viewer asleep' })+ await vi.advanceTimersByTimeAsync(3000)+ expect(callback).toHaveBeenLastCalledWith(expect.objectContaining({ state: 'live' }))+ renderers.at(-1)!.capture.mockRejectedValueOnce('opaque failure')+ await vi.advanceTimersByTimeAsync(400)+ expect(callback).toHaveBeenLastCalledWith(expect.objectContaining({ message: 'The viewer is temporarily unavailable.' }))+ })+ it('does not leak a camera or emit frames when the last viewer leaves during startup', async () => {+ target = 'http://localhost:1234'+ let finish!: () => void+ create.mockImplementationOnce(() => {+ const renderer = { start: vi.fn(() => new Promise<void>(resolve => { finish = resolve })), capture: vi.fn(), stop: vi.fn(async () => {}) }+ renderers.push(renderer); return renderer as unknown as ViewerCapture+ })+ const callback = vi.fn(), leave = pool.watch('agent', callback)+ await flush(); leave(); finish(); await flush()+ expect(renderers[0].stop).toHaveBeenCalledTimes(1)+ expect(renderers[0].capture).not.toHaveBeenCalled()+ expect(callback).toHaveBeenCalledTimes(1)+ })+ it('contains late errors and a stopped target switch without reopening the renderer', async () => {+ target = 'http://localhost:1234'; const callback = vi.fn(), leave = pool.watch('agent', callback)+ await flush()+ let fail!: (reason: unknown) => void+ renderers[0].capture.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject }))+ await vi.advanceTimersByTimeAsync(400); leave(); fail(new Error('late failure')); await flush()+ expect(callback).not.toHaveBeenCalledWith(expect.objectContaining({ state: 'unavailable' }))+ pool.watch('another', callback); await flush()+ let stop!: () => void+ renderers.at(-1)!.stop.mockImplementationOnce(() => new Promise<void>(resolve => { stop = resolve }))+ target = 'http://localhost:2345'; await vi.advanceTimersByTimeAsync(400)+ const count = create.mock.calls.length; pool.stop(); stop(); await flush()+ expect(create).toHaveBeenCalledTimes(count)+ })+ it('can use the production renderer factory', async () => {+ const production = new SharedViewerPool(() => 'http://localhost:1234')+ const callback = vi.fn(); const stop = production.watch('agent', callback)+ await flush(); stop(); production.stop()+ expect(callback).toHaveBeenCalledWith({ state: 'loading' })+ })+})diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dartindex 9149ffd3c..7f8ed6eaf 100644--- a/desktop/lib/sharing/share_harness_dialog.dart+++ b/desktop/lib/sharing/share_harness_dialog.dart@@ -290,8 +290,8 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {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.',+ 'They’ll find this harness in Machines → Shared with you using the invited email. '+ 'Keep your machine online while they watch. You can remove access at any time.',style: TextStyle(fontSize: 12, height: 1.5),),),diff --git a/desktop/lib/widgets/machine_rail.dart b/desktop/lib/widgets/machine_rail.dartindex 4723faa86..12be9cfea 100644--- a/desktop/lib/widgets/machine_rail.dart+++ b/desktop/lib/widgets/machine_rail.dart@@ -873,11 +873,12 @@ class _AgentTree extends StatelessWidget {// nobody finds who does not already know it. Put where a new row would actually appear, it needs no// discovering. It joins `rows` rather than being appended after the loop so the guide's trunk runs// down to it and closes there, exactly as it would on a real last agent.- if (!state.machine.isShared) _NewAgentRow(- notifier: notifier,- machineId: state.machine.machineId,- source: 'rail_tail',- ),+ if (!state.machine.isShared)+ _NewAgentRow(+ notifier: notifier,+ machineId: state.machine.machineId,+ source: 'rail_tail',+ ),];return Column(diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 38682a114..b8b05a62e 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -297,8 +297,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private func rebuildMachinesMenu() {machinesMenu.removeAllItems()machinesMenu.minimumWidth = 0- let labels = machines.map { machine -> (name: String, presence: String, status: String, count: String) in+ let labels = machines.map { machine -> (name: String, owner: String, presence: String, status: String, count: String) in(name: SwarmMenuText.fitted(machine.name, width: 200),+ owner: machine.shared && !machine.ownerName.isEmpty ? " · " + SwarmMenuText.fitted(machine.ownerName, width: 140) : "",// Node presence ("Online"/"Offline"), shown grey right after the name,// independent of the link state on the trailing edge.presence: machine.presence,@@ -309,7 +310,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {// Leading text = name + presence; trailing column = the agent count, or the// status word ("Link required"/"Offline"/…) when there is no count.let compactEdge = SwarmMenuText.trailingEdge(labels.map {- ($0.presence.isEmpty ? $0.name : $0.name + " " + $0.presence,+ ($0.name + $0.owner + ($0.presence.isEmpty ? "" : " " + $0.presence),$0.count.isEmpty ? $0.status : $0.count)})let trailingEdge = ceil((compactEdge + 62) * 1.2) - 62@@ -339,8 +340,7 @@ 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 owner = machine.shared && !machine.ownerName.isEmpty ? " · " + machine.ownerName : ""- let afterName = owner + (parts.presence.isEmpty ? "" : " " + parts.presence)+ let afterName = parts.owner + (parts.presence.isEmpty ? "" : " " + parts.presence)let trailing = parts.count.isEmpty ? parts.status : parts.countlabel.append(NSAttributedString(string: afterName + "\t" + trailing,attributes: [.font: NSFont.menuFont(ofSize: 0), .paragraphStyle: paragraph,@@ -506,9 +506,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {modelsMenu.addItem(caption)let run = NSMenuItem(title: "Talk to Model manager", action: nil, keyEquivalent: "")run.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "runLocalModel")- if machines.count > 1 {+ if machines.filter({ !$0.shared }).count > 1 {let pick = NSMenu(title: run.title)- for machine in machines {+ for machine in machines where !machine.shared {let item = NSMenuItem(title: machine.local ? "\(machine.name) (this computer)" : machine.name,action: #selector(runLocalModelAction(_:)), keyEquivalent: "")item.target = selfdiff --git a/desktop/test/api_client_test.dart b/desktop/test/api_client_test.dartindex 48e61c34b..14874ed58 100644--- a/desktop/test/api_client_test.dart+++ b/desktop/test/api_client_test.dart@@ -11,11 +11,11 @@ import 'package:flutter_test/flutter_test.dart';void main() {test('machine request hits the local CLI proxy, not the backend, with no credential', () async {final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);- final path = Completer<String?>();- final hadAuthHeader = Completer<bool>();+ final paths = <String>[];+ final hadAuthHeaders = <bool>[];final subscription = server.listen((request) async {- path.complete(request.uri.path);- hadAuthHeader.complete(request.headers.value('authorization') != null);+ paths.add(request.uri.path);+ hadAuthHeaders.add(request.headers.value('authorization') != null);request.response..statusCode = HttpStatus.ok..headers.contentType = ContentType.json@@ -47,8 +47,8 @@ void main() {);final machines = await api.machines();- expect(await path.future, '/api/machines');- expect(await hadAuthHeader.future, isFalse);+ expect(paths, ['/api/machines', '/api/harness-shares']);+ expect(hadAuthHeaders, [false, false]);expect(machines.single.machineId, 'machine-1');expect(machines.single.computerId, '0123456789abcdef0123456789abcdef');} finally {@@ -100,6 +100,42 @@ void main() {}});+ test('shared discovery keeps offline grants through outages, clears revoked entries and supports older daemons', () async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ var shareStatus = 200;+ var shares = <Map<String, dynamic>>[+ {'machineId': 'shared', 'shared': true, 'authMode': 'remote', 'status': 'offline', 'ownerName': 'D', 'name': 'Studio',+ 'shares': [{'id': 'grant', 'agentId': 'agent', 'name': 'Climate dashboard', 'engine': 'codex', 'expiresAt': '2027-01-01T00:00:00Z'}]},+ {'machineId': 'owned', 'shared': true, 'authMode': 'remote', 'shares': []},+ ];+ server.listen((request) async {+ final sharing = request.uri.path == '/api/harness-shares';+ request.response.statusCode = sharing ? shareStatus : 200;+ request.response.headers.contentType = ContentType.json;+ request.response.write(jsonEncode({'success': shareStatus == 200 || !sharing, 'data': {'machines': sharing ? shares : [+ {'machineId': 'owned', 'authMode': 'remote', 'name': 'This computer'},+ ]}, 'error': {'code': 'UNAVAILABLE', 'message': 'Temporary outage'}}));+ await request.response.close();+ });+ try {+ final api = ApiClient(config: AppConfig(apiBaseUrl: 'http://unused.invalid', localCliBaseUrl: 'http://127.0.0.1:${server.port}'), session: AuthSession());+ final first = await api.machines();+ expect(first.map((m) => m.machineId), ['owned', 'shared']);+ final shared = first.last;+ expect(shared.isShared, isTrue); expect(shared.status, 'offline'); expect(shared.ownerName, 'D');+ expect(shared.sharedHarnesses.single.agentId, 'agent');+ expect(shared.copyWith(name: 'Updated').sharedHarnesses.single.id, 'grant');+ shareStatus = 503;+ expect((await api.machines()).last.machineId, 'shared'); expect(api.lastMachinesStale, isTrue);+ shareStatus = 200; shares = [];+ expect((await api.machines()).map((m) => m.machineId), ['owned']); expect(api.lastMachinesStale, isFalse);+ shareStatus = 404;+ expect((await api.machines()).single.machineId, 'owned'); expect(api.lastMachinesStale, isFalse);+ shareStatus = 401;+ await expectLater(api.machines(), throwsA(isA<ApiException>()));+ } finally { await server.close(force: true); }+ });+group('describeApiError', () {final options = RequestOptions(path: '/api/machines',diff --git a/desktop/test/machines_menu_test.dart b/desktop/test/machines_menu_test.dartindex 9c6cd6e21..4545f935a 100644--- a/desktop/test/machines_menu_test.dart+++ b/desktop/test/machines_menu_test.dart@@ -9,6 +9,7 @@ import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/screens/swarm_screen.dart';import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/state/app_state.dart';import 'package:harness/terminal/terminal_binary.dart';import 'swarm_state_test.dart' show createApp;@@ -26,6 +27,32 @@ class _RecordingApi extends ApiClient {}void main() {+ testWidgets('shared machines expose only invited agents and carry a view-only owner label', (tester) async {+ const channel = MethodChannel('harness/swarm_tabs');+ final messages = <MethodCall>[];+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async { messages.add(call); return true; });+ addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));+ final app = createApp();+ final grant = SharedHarness(id: 'grant', agentId: 'shared-agent', name: 'Climate dashboard', expiresAt: DateTime(2027));+ final shared = Machine(machineId: 'shared', authMode: MachineAuthMode.remote, name: 'Studio', isShared: true, ownerName: 'D', sharedHarnesses: [grant]);+ app.machines.add(shared);+ app.machineStates['shared'] = MachineState(shared)+ ..nodeOnline = true+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [const Agent(id: 'shared-agent', name: 'Climate dashboard', terminalAvailable: true)];+ final projects = SwarmProjectStore();+ await tester.pumpWidget(MaterialApp(home: SwarmScreen(notifier: app, nativeTabs: true, projectStore: projects)));+ await tester.pump();+ final state = messages.lastWhere((m) => m.method == 'machinesState').arguments as Map;+ final machines = state['machines'] as List;+ final row = machines.cast<Map>().firstWhere((m) => m['id'] == 'shared');+ expect(row['shared'], isTrue); expect(row['ownerName'], 'D');+ expect(row['linkRequired'], isFalse);+ expect((row['agents'] as List).single, containsPair('id', 'shared-agent'));+ expect((row['agents'] as List).single, containsPair('canOpen', true));+ expect(app.machineStates['shared']!.connectionStatus, ConnectionStatus.disconnected);+ await tester.pumpWidget(const SizedBox()); app.dispose(); projects.dispose();+ });testWidgets('tab navigation does not resend the agent inventory', (tester,) async {diff --git a/desktop/test/share_harness_test.dart b/desktop/test/share_harness_test.dartindex 07ae235a4..adfc7f163 100644--- a/desktop/test/share_harness_test.dart+++ b/desktop/test/share_harness_test.dart@@ -4,6 +4,7 @@ import 'dart:ui' as ui;import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/sharing/share_harness_dialog.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;@@ -12,133 +13,247 @@ import 'package:harness/ws/ws_conn.dart';import 'support/real_fonts.dart';void main() {- setUpAll(loadRealFonts);- Future<void> show(WidgetTester tester, ShareAction manage, {Size size = const Size(900, 800)}) async {+ setUpAll(() async {+ await loadRealFonts();+ await (FontLoader(+ 'MaterialIcons',+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();+ });+ Future<void> show(+ WidgetTester tester,+ ShareAction manage, {+ Size size = const Size(900, 800),+ }) async {tester.view.physicalSize = size;tester.view.devicePixelRatio = 1;addTearDown(tester.view.reset);- await tester.pumpWidget(MaterialApp(- theme: grid.buildAppTheme(brightness: Brightness.dark),- home: RepaintBoundary(key: const Key('sharing-preview'), child: Scaffold(- body: Builder(builder: (context) => TextButton(onPressed: () {- showDialog<void>(context: context, builder: (_) => ShareHarnessDialog(name: 'Climate dashboard', manage: manage));- }, child: const Text('Open share'))),- )),- ));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: RepaintBoundary(+ key: const Key('sharing-preview'),+ child: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () {+ showDialog<void>(+ context: context,+ builder: (_) => RepaintBoundary(+ key: const Key('sharing-dialog-preview'),+ child: ShareHarnessDialog(+ name: 'Climate dashboard',+ manage: manage,+ ),+ ),+ );+ },+ child: const Text('Open share'),+ ),+ ),+ ),+ ),+ ),+ );await tester.tap(find.text('Open share'));- await tester.pump(); await tester.pump(const Duration(milliseconds: 300));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 300));}- Map<String, dynamic> person(String email, {String? error, bool pending = false, bool expired = false, int watching = 0}) => {- 'id': email, 'email': email, 'expiresAt': '2026-10-17T00:00:00.000Z',- 'error': error, 'pending': pending, 'expired': expired, 'watching': watching,++ Map<String, dynamic> person(+ String email, {+ String? error,+ bool pending = false,+ bool expired = false,+ int watching = 0,+ }) => {+ 'id': email,+ 'email': email,+ 'expiresAt': '2026-10-17T00:00:00.000Z',+ 'error': error,+ 'pending': pending,+ 'expired': expired,+ 'watching': watching,};final submit = find.widgetWithText(FilledButton, 'Share harness');- testWidgets('invites normalized emails, shows live presence and immediately removes access', (tester) async {- var shares = <Map<String, dynamic>>[];- final calls = <(String, Map<String, dynamic>)>[];- await show(tester, (action, payload) async {- calls.add((action, payload));- if (action == 'invite') shares = [person('[email protected]', watching: 1), person('[email protected]')];- if (action == 'remove') shares.removeWhere((row) => row['id'] == payload['id']);- return {'shares': shares};- });- expect(find.text('Only you have access.'), findsOneWidget);- expect(find.text('Can view'), findsOneWidget);- await tester.enterText(find.byType(TextField), '[email protected]; [email protected], [email protected]');- await tester.tap(submit); await tester.pump();- expect(calls.last, ('invite', {'emails': ['[email protected]', '[email protected]'], 'days': 30}));- expect(find.text('2 people now have view-only access.'), findsOneWidget);- expect(find.text('Watching now · Can view'), findsOneWidget);- expect(find.textContaining('Shared with you'), findsOneWidget);- expect(tester.takeException(), isNull);- // Optional artifact for visual review; no golden files or production filesystem writes.- final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];- if (output != null) {- final boundary = tester.firstRenderObject<RenderRepaintBoundary>(find.byType(RepaintBoundary));- final image = await boundary.toImage();- final png = await image.toByteData(format: ui.ImageByteFormat.png);- await tester.runAsync(() => File(output).writeAsBytes(png!.buffer.asUint8List()));- image.dispose();- }- await tester.tap(find.widgetWithText(TextButton, 'Remove').first); await tester.pump();- expect(calls.last, ('remove', {'id': '[email protected]'}));- expect(find.text('[email protected]'), findsNothing);- expect(find.text('Access removed.'), findsOneWidget);- await tester.pump(const Duration(seconds: 5));- expect(calls.last.$1, 'list');- await tester.tap(find.text('Done')); await tester.pumpAndSettle();- expect(find.text('Share harness'), findsNothing);- });+ testWidgets(+ 'invites normalized emails, shows live presence and immediately removes access',+ (tester) async {+ var shares = <Map<String, dynamic>>[];+ final calls = <(String, Map<String, dynamic>)>[];+ await show(tester, (action, payload) async {+ calls.add((action, payload));+ if (action == 'invite')+ shares = [+ person('[email protected]', watching: 1),+ person('[email protected]'),+ ];+ if (action == 'remove')+ shares.removeWhere((row) => row['id'] == payload['id']);+ return {'shares': shares};+ });+ expect(find.text('Only you have access.'), findsOneWidget);+ expect(find.text('Can view'), findsOneWidget);+ await tester.enterText(+ find.byType(TextField),+ );+ await tester.tap(submit);+ await tester.pump();+ expect(calls.last.$1, 'invite');+ expect(calls.last.$2, {+ 'emails': ['[email protected]', '[email protected]'],+ 'days': 30,+ });+ expect(find.text('2 people now have view-only access.'), findsOneWidget);+ expect(find.text('Watching now · Can view'), findsOneWidget);+ expect(find.textContaining('Shared with you'), findsOneWidget);+ expect(tester.takeException(), isNull);+ // Optional artifact for visual review; no golden files or production filesystem writes.+ final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];+ if (output != null) {+ final boundary = tester.renderObject<RenderRepaintBoundary>(+ find.byKey(const Key('sharing-dialog-preview')),+ );+ await tester.pump();+ await tester.runAsync(() async {+ final image = await boundary.toImage();+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File(output).writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ }+ await tester.tap(find.widgetWithText(TextButton, 'Remove').first);+ await tester.pump();+ expect(calls.last.$1, 'remove');+ expect(calls.last.$2, {'id': '[email protected]'});+ expect(find.text('[email protected]'), findsNothing);+ expect(find.text('Access removed.'), findsOneWidget);+ await tester.pump(const Duration(seconds: 5));+ expect(calls.last.$1, 'list');+ await tester.tap(find.text('Done'));+ await tester.pumpAndSettle();+ expect(find.text('Share harness'), findsNothing);+ },+ );- testWidgets('validates addresses locally and prevents duplicate submissions while saving', (tester) async {- final pending = Completer<Map<String, dynamic>>();- var invites = 0;- await show(tester, (action, _) async {- if (action == 'invite') { invites++; return pending.future; }- return {'shares': []};- });- for (final invalid in ['', 'bad', List.generate(21, (i) => '[email protected]').join(',')]) {- await tester.enterText(find.byType(TextField), invalid);- await tester.tap(submit); await tester.pump();- expect(find.textContaining('Enter up to 20 valid'), findsOneWidget);- }- expect(invites, 0);- await tester.enterText(find.byType(TextField), '[email protected]');- await tester.tap(submit); await tester.pump();- expect(find.text('Saving…'), findsOneWidget);- expect(tester.widget<FilledButton>(find.byType(FilledButton)).onPressed, isNull);- await tester.pump(const Duration(seconds: 5));- expect(invites, 1);- pending.complete({'shares': [person('[email protected]', pending: true)]}); await tester.pump();- expect(find.text('Waiting for connection'), findsOneWidget);- expect(find.textContaining('Invitations saved.'), findsOneWidget);- await tester.pumpWidget(const SizedBox());- });+ testWidgets(+ 'validates addresses locally and prevents duplicate submissions while saving',+ (tester) async {+ final pending = Completer<Map<String, dynamic>>();+ var invites = 0;+ await show(tester, (action, _) async {+ if (action == 'invite') {+ invites++;+ return pending.future;+ }+ return {'shares': []};+ });+ for (final invalid in [+ '',+ 'bad',+ List.generate(21, (i) => '[email protected]').join(','),+ ]) {+ await tester.enterText(find.byType(TextField), invalid);+ await tester.tap(submit);+ await tester.pump();+ expect(find.textContaining('Enter up to 20 valid'), findsOneWidget);+ }+ expect(invites, 0);+ await tester.enterText(find.byType(TextField), '[email protected]');+ await tester.tap(submit);+ await tester.pump();+ expect(find.text('Saving…'), findsOneWidget);+ expect(+ tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,+ isNull,+ );+ await tester.pump(const Duration(seconds: 5));+ expect(invites, 1);+ pending.complete({+ 'shares': [person('[email protected]', pending: true)],+ });+ await tester.pump();+ await tester.pump();+ expect(find.text('Waiting for connection'), findsOneWidget);+ expect(find.textContaining('Invitations saved.'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );- testWidgets('renders pending, expired and rejected grants clearly at a narrow width', (tester) async {- await show(tester, (_, _) async => {'shares': [- person('[email protected]', pending: true), person('[email protected]', expired: true),- person('[email protected]', error: 'You already own this harness.'),- ]}, size: const Size(440, 680));- expect(find.text('Waiting for connection'), findsOneWidget);- expect(find.text('Expired · add again to renew'), findsOneWidget);- expect(find.text('You already own this harness.'), findsOneWidget);- expect(tester.takeException(), isNull);- await tester.pumpWidget(const SizedBox());- });+ testWidgets(+ 'renders pending, expired and rejected grants clearly at a narrow width',+ (tester) async {+ await show(+ tester,+ (_, _) async => {+ 'shares': [+ person('[email protected]', pending: true),+ person('[email protected]', expired: true),+ person('[email protected]', error: 'You already own this harness.'),+ ],+ },+ size: const Size(440, 680),+ );+ expect(find.text('Waiting for connection'), findsOneWidget);+ expect(find.text('Expired · add again to renew'), findsOneWidget);+ expect(find.text('You already own this harness.'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ );- testWidgets('shows actionable errors, recovers on retry and survives dismissal during a request', (tester) async {- var fails = true;- await show(tester, (_, _) async {- if (fails) throw const WsRequestFailure(responseType: 'harness_share_list_result', code: 'UNSUPPORTED');- return {'shares': []};- });- expect(find.text('Update Harness on this machine to start sharing.'), findsOneWidget);- fails = false;- await tester.tap(find.text('Retry')); await tester.pump();- expect(find.text('Only you have access.'), findsOneWidget);- expect(find.text('Retry'), findsNothing);- await tester.pumpWidget(const SizedBox());- final pending = Completer<Map<String, dynamic>>();- await show(tester, (_, _) => pending.future);- await tester.tap(find.text('Done')); await tester.pumpAndSettle();- pending.complete({'shares': []}); await tester.pump();- expect(tester.takeException(), isNull);- });+ testWidgets(+ 'shows actionable errors, recovers on retry and survives dismissal during a request',+ (tester) async {+ var fails = true;+ await show(tester, (_, _) async {+ if (fails)+ throw const WsRequestFailure(+ responseType: 'harness_share_list_result',+ code: 'UNSUPPORTED',+ );+ return {'shares': []};+ });+ expect(+ find.text('Update Harness on this machine to start sharing.'),+ findsOneWidget,+ );+ fails = false;+ await tester.tap(find.text('Retry'));+ await tester.pump();+ expect(find.text('Only you have access.'), findsOneWidget);+ expect(find.text('Retry'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ final pending = Completer<Map<String, dynamic>>();+ await show(tester, (_, _) => pending.future);+ await tester.tap(find.text('Done'));+ await tester.pumpAndSettle();+ pending.complete({'shares': []});+ await tester.pump();+ expect(tester.takeException(), isNull);+ },+ );- testWidgets('a stale presence refresh cannot erase a newly saved invitation', (tester) async {- var lists = 0;- final stale = Completer<Map<String, dynamic>>();- await show(tester, (action, _) async {- if (action == 'list' && ++lists > 1) return stale.future;- return {'shares': action == 'invite' ? [person('[email protected]')] : []};- });- await tester.pump(const Duration(seconds: 5));- await tester.enterText(find.byType(TextField), '[email protected]');- await tester.tap(submit); await tester.pump();- stale.complete({'shares': []}); await tester.pump();- expect(find.text('[email protected]'), findsOneWidget);- await tester.pumpWidget(const SizedBox());- });+ testWidgets(+ 'a stale presence refresh cannot erase a newly saved invitation',+ (tester) async {+ var lists = 0;+ final stale = Completer<Map<String, dynamic>>();+ await show(tester, (action, _) async {+ if (action == 'list' && ++lists > 1) return stale.future;+ return {+ 'shares': action == 'invite' ? [person('[email protected]')] : [],+ };+ });+ await tester.pump(const Duration(seconds: 5));+ await tester.enterText(find.byType(TextField), '[email protected]');+ await tester.tap(submit);+ await tester.pump();+ stale.complete({'shares': []});+ await tester.pump();+ expect(find.text('[email protected]'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );}diff --git a/desktop/test/shared_harness_panel_test.dart b/desktop/test/shared_harness_panel_test.dartnew file mode 100644index 000000000..56c3a66db--- /dev/null+++ b/desktop/test/shared_harness_panel_test.dart@@ -0,0 +1,262 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/sharing/shared_harness_panel.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/terminal/terminal_binary.dart';++import 'support/real_fonts.dart';++void main() {+ setUpAll(() async {+ await loadRealFonts();+ HttpOverrides.global = null;+ });+ const streamId = '00112233-4455-6677-8899-aabbccddeeff';+ testWidgets(+ 'read-only terminal receives output, keeps its lease alive and never sends input or resize',+ (tester) async {+ final sent = <Map<String, dynamic>>[], binary = <TerminalBinaryFrame>[];+ final session = TerminalSession(+ machineId: 'shared',+ agentId: 'agent',+ agentName: 'Demo',+ engineId: 'codex',+ readOnly: true,+ send: (type, payload) async {+ sent.add({'type': type, ...payload});+ return true;+ },+ sendBinary: (frame) async {+ binary.add(frame);+ return true;+ },+ );+ await session.open();+ await session.handleFrame('terminal_ready', {+ 'requestId': sent.first['requestId'],+ 'protocolVersion': 3,+ 'streamId': streamId,+ 'agentId': 'agent',+ });+ await session.handleBinary(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.keyframe,+ streamId: streamId,+ seq: 0,+ bytes: Uint8List.fromList(utf8.encode('Live shared output')),+ compressed: false,+ cols: 110,+ rows: 33,+ ),+ );+ expect(session.terminal.buffer.getText(), contains('Live shared output'));+ expect(session.acceptsInput, isFalse);+ session.terminal.textInput('forbidden');+ session.resize(12, 12);+ expect(await session.sendComposerText('forbidden'), isFalse);+ expect(await session.pasteText('forbidden'), isFalse);+ session.sendScrollCommand(true, 10);+ await tester.pump(const Duration(seconds: 15));+ expect(+ sent.where((frame) => frame['type'] == 'terminal_alive'),+ isNotEmpty,+ );+ expect(+ sent.where((frame) => frame['type'] == 'terminal_resize'),+ isEmpty,+ );+ expect(binary, isEmpty);+ session.dispose();+ },+ );++ for (final width in [1100.0, 620.0]) {+ testWidgets(+ 'shared pane live output, reconnect, revocation and renewal at width $width',+ (tester) async {+ tester.view.physicalSize = Size(width, 760);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ final sockets = <WebSocket>[], requests = <Map<String, dynamic>>[];+ final closingSockets = <WebSocket>{};+ late HttpServer server;+ await tester.runAsync(() async {+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ server.listen((request) async {+ final ws = await WebSocketTransformer.upgrade(request);+ sockets.add(ws);+ ws.listen((raw) {+ if (closingSockets.contains(ws) || ws.readyState != WebSocket.open) return;+ if (raw is! String) {+ fail('An observer sent terminal bytes');+ return;+ }+ final frame = jsonDecode(raw) as Map<String, dynamic>;+ requests.add(frame);+ final p = frame['payload'] as Map;+ if (frame['type'] == 'machine_select') {+ ws.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {'machineId': 'shared', 'readOnly': true},+ }),+ );+ } else if (frame['type'] == 'terminal_open') {+ ws.add(+ jsonEncode({+ 'type': 'terminal_ready',+ 'payload': {+ 'requestId': p['requestId'],+ 'protocolVersion': 3,+ 'streamId': streamId,+ 'agentId': 'agent',+ 'readOnly': true,+ },+ }),+ );+ ws.add(+ encodeTerminalLocal(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.keyframe,+ streamId: streamId,+ seq: 0,+ bytes: Uint8List.fromList(+ utf8.encode('LIVE_OBSERVER_OUTPUT'),+ ),+ compressed: false,+ cols: 110,+ rows: 33,+ ),+ )!,+ );+ } else if (frame['type'] == 'observer_viewer') {+ ws.add(+ jsonEncode({+ 'type': 'observer_viewer',+ 'payload': {+ 'state': 'waiting',+ 'message': 'The viewer will appear when this harness produces an output.',+ },+ }),+ );+ }+ });+ });+ });+ final app = AppNotifier(+ config: AppConfig(+ apiBaseUrl: 'http://127.0.0.1:9',+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',+ ),+ authSession: AuthSession(),+ configStore: null,+ );+ final grant = SharedHarness(+ id: 'grant',+ agentId: 'agent',+ name: 'Climate dashboard',+ engine: 'codex',+ expiresAt: DateTime(2027),+ );+ final pane = TerminalPane(id: 1, machineId: 'shared', agentId: 'agent')+ ..sharedHarness = grant+ ..sharedOwnerName = 'D';+ var hasAccess = true, closePressed = false;+ Future<void> draw() => tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SharedHarnessPanel(+ notifier: app,+ pane: pane,+ grant: grant,+ hasAccess: hasAccess,+ visible: true,+ onClose: () => closePressed = true,+ ),+ ),+ ),+ );+ Future<void> settleNetwork(bool Function() ready) async {+ for (var i = 0; i < 100; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 20)),+ );+ await tester.pump();+ if (ready()) return;+ }+ fail('Observer UI did not reach expected state');+ }++ await draw();+ await settleNetwork(() => find.text('Live').evaluate().isNotEmpty);+ expect(requests.first['payload'], containsPair('shareId', 'grant'));+ expect(find.text('View only'), findsOneWidget);+ await settleNetwork(+ () => requests.any((r) => r['type'] == 'observer_viewer'),+ );+ if (width < 880) {+ await tester.tap(find.text('Viewer'));+ await tester.pump();+ }+ expect(find.textContaining('The viewer will appear'), findsOneWidget);+ expect(+ requests.map((r) => r['type']),+ isNot(contains('terminal_resize')),+ );+ expect(tester.takeException(), isNull);+ await tester.runAsync(() async {+ closingSockets.add(sockets.last);+ await sockets.last.close(1001, 'Owner disconnected');+ });+ await settleNetwork(+ () => find.text('Reconnecting').evaluate().isNotEmpty,+ );+ await tester.pump(const Duration(seconds: 1));+ await settleNetwork(+ () => sockets.length == 2 && find.text('Live').evaluate().isNotEmpty,+ );+ await tester.runAsync(() async {+ closingSockets.add(sockets.last);+ await sockets.last.close(4403, 'Access removed');+ });+ await settleNetwork(+ () => find.text('Sharing ended').evaluate().isNotEmpty,+ );+ expect(find.text('Access removed'), findsOneWidget);+ await tester.pump(const Duration(seconds: 30));+ expect(sockets.length, 2);+ hasAccess = false;+ await draw();+ hasAccess = true;+ await draw();+ await settleNetwork(+ () => sockets.length == 3 && find.text('Live').evaluate().isNotEmpty,+ );+ await tester.tap(find.byTooltip('Close shared harness'));+ expect(closePressed, isTrue);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ await tester.runAsync(() async {+ for (final ws in sockets) {+ closingSockets.add(ws);+ unawaited(ws.close());+ }+ await server.close(force: true);+ });+ await tester.pump(const Duration(seconds: 6));+ },+ );+ }+}