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
Add an experimental Devices DSH for account-wide hardware control (#571)
Dee1c558e2ed431
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex a1c22298f..edb548fb4 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -659,6 +659,7 @@ model ExperimentalSettings {userId StringfocusBarCreature Boolean @default(false)shareButton Boolean @default(false)+ devicesTab Boolean @default(false)revision Int @default(0)@@index([userId])diff --git a/backend/src/lib/experimentalSettings.ts b/backend/src/lib/experimentalSettings.tsindex 01b3ee899..e7b05b2a8 100644--- a/backend/src/lib/experimentalSettings.ts+++ b/backend/src/lib/experimentalSettings.ts@@ -2,14 +2,14 @@ import { createHash } from 'node:crypto'import { Prisma } from '@prisma/client'import { prisma } from './prisma.js'-export const experimentalFeatures = ['focus_bar_creature', 'share_button'] as const+export const experimentalFeatures = ['focus_bar_creature', 'share_button', 'devices_tab'] as constexport type ExperimentalFeature = typeof experimentalFeatures[number]export const experimentalSettingsId = (userId: string): string =>createHash('sha256').update(JSON.stringify(['experimental-settings', userId])).digest('hex').slice(0, 24)-const snapshot = (row: { focusBarCreature: boolean; shareButton: boolean; revision: number } | null) => ({+const snapshot = (row: { focusBarCreature: boolean; shareButton: boolean; devicesTab?: boolean; revision: number } | null) => ({revision: row?.revision ?? 0,- features: { focus_bar_creature: row?.focusBarCreature === true, share_button: row?.shareButton === true },+ features: { focus_bar_creature: row?.focusBarCreature === true, share_button: row?.shareButton === true, devices_tab: row?.devicesTab === true },})/** Reading never opts an account in or imports an installation's unscoped preferences. */@@ -22,12 +22,12 @@ export async function readExperimentalSettings(userId: string) {/** Change one field atomically so two machines editing different switches keep both choices. */export async function setExperimentalSetting(userId: string, feature: ExperimentalFeature, enabled: boolean) {const id = experimentalSettingsId(userId)- const field = feature === 'focus_bar_creature' ? 'focusBarCreature' : 'shareButton'+ const field = { focus_bar_creature: 'focusBarCreature', share_button: 'shareButton', devices_tab: 'devicesTab' }[feature]const data = { [field]: enabled, revision: { increment: 1 } }let rowtry {row = await prisma.experimentalSettings.upsert({ where: { id },- create: { id, userId, focusBarCreature: false, shareButton: false, [field]: enabled, revision: 1 },+ create: { id, userId, focusBarCreature: false, shareButton: false, devicesTab: false, [field]: enabled, revision: 1 },update: data })} catch (error) {if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw errordiff --git a/backend/src/routes/experimentalSettings.test.ts b/backend/src/routes/experimentalSettings.test.tsindex 98e457ae8..e10512dfd 100644--- a/backend/src/routes/experimentalSettings.test.ts+++ b/backend/src/routes/experimentalSettings.test.ts@@ -16,7 +16,7 @@ import { DAEMONS_DARK, DAEMONS_EVERYONE, type DaemonsSwitch } from '../lib/daemoimport { registerAuthMiddleware } from '../middlewares/authMiddleware.js'import { errorHandler } from '../middlewares/errorHandler.js'-type Row = { id: string; userId: string; focusBarCreature: boolean; shareButton: boolean; revision: number }+type Row = { id: string; userId: string; focusBarCreature: boolean; shareButton: boolean; devicesTab?: boolean; revision: number }describe('account experiments and retained collections', () => {let app: FastifyInstancelet rows: Map<string, Row>@@ -34,7 +34,7 @@ describe('account experiments and retained collections', () => {mocks.prisma.experimentalSettings.findUnique.mockImplementation(async ({ where }) => rows.get(where.id) ?? null)mocks.prisma.experimentalSettings.update.mockImplementation(async ({ where, data }) => {const row = { ...rows.get(where.id)! }- for (const key of ['focusBarCreature', 'shareButton'] as const) if (key in data) row[key] = data[key]+ for (const key of ['focusBarCreature', 'shareButton', 'devicesTab'] as const) if (key in data) row[key] = data[key]row.revision++; rows.set(row.id, row); return row})mocks.prisma.experimentalSettings.upsert.mockImplementation(async ({ where, create, update }) => {@@ -55,7 +55,7 @@ describe('account experiments and retained collections', () => {expect((await app.inject({ method: 'GET', url: '/api/experimental-settings' })).statusCode).toBe(401)expect(mocks.prisma.experimentalSettings.findUnique).not.toHaveBeenCalled()expect((await read()).json().data).toEqual({ accountId: 'owner', revision: 0,- features: { focus_bar_creature: false, share_button: false }, available: { focus_bar_creature: true, share_button: true } })+ features: { focus_bar_creature: false, share_button: false, devices_tab: false }, available: { focus_bar_creature: true, share_button: true, devices_tab: true } })expect(rows.size).toBe(0)expect((await zoo()).statusCode).toBe(404)expect(mocks.prisma.zoo.findUnique).not.toHaveBeenCalled()@@ -63,10 +63,21 @@ describe('account experiments and retained collections', () => {it('shares choices between clients without losing concurrent changes to different switches', async () => {expect((await Promise.all([write('focus_bar_creature', true), write('share_button', true)])).map(r => r.statusCode)).toEqual([200, 200])expect((await read()).json().data).toMatchObject({ revision: 2, features: { focus_bar_creature: true, share_button: true } })- expect((await write('share_button', false)).json().data.features).toEqual({ focus_bar_creature: true, share_button: false })+ expect((await write('share_button', false)).json().data.features).toEqual({ focus_bar_creature: true, share_button: false, devices_tab: false })expect(mocks.deskChanged).toHaveBeenCalledWith('owner', { revision: 0 })expect(mocks.zooChanged).toHaveBeenCalledExactlyOnceWith('owner', { revision: 0 })})+ it('keeps Devices off for existing accounts and changes only the requested flag', async () => {+ const id = experimentalSettingsId('owner')+ rows.set(id, { id, userId: 'owner', focusBarCreature: false, shareButton: true, revision: 8 })+ expect((await read()).json().data.features.devices_tab).toBe(false)+ expect((await write('devices_tab', true)).json().data.features).toEqual({+ focus_bar_creature: false, share_button: true, devices_tab: true,+ })+ expect((await write('devices_tab', false)).json().data.features.devices_tab).toBe(false)+ mocks.auth.mockResolvedValue({ sub: 'second', role: 'user' })+ expect((await read()).json().data.features.devices_tab).toBe(false)+ })it('rejects malformed writes and requests created before an account switch', async () => {expect((await write('focus_bar_creature', true, 'another-account')).statusCode).toBe(409)expect((await write('unknown', true)).statusCode).toBe(400)diff --git a/backend/src/routes/experimentalSettings.ts b/backend/src/routes/experimentalSettings.tsindex e69590a50..327f8e87b 100644--- a/backend/src/routes/experimentalSettings.ts+++ b/backend/src/routes/experimentalSettings.ts@@ -10,7 +10,7 @@ const settingBody = z.object({ accountId: z.string().min(1).max(200), feature: zexport async function experimentalSettingsRoutes(app: FastifyInstance, opts: { daemons?: DaemonsSwitch } = {}) {const available = (user: { sub: string; email?: string | null } | undefined) => ({- focus_bar_creature: daemonsFor(opts.daemons ?? DAEMONS_DARK, user), share_button: true,+ focus_bar_creature: daemonsFor(opts.daemons ?? DAEMONS_DARK, user), share_button: true, devices_tab: true,})app.get('/api/experimental-settings', async (req, reply) => {sendSuccess(reply, { accountId: req.user!.sub, ...await readExperimentalSettings(req.user!.sub), available: available(req.user) })diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex ef86bde49..3ea933127 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -12,11 +12,12 @@import * as esbuild from 'esbuild'import { readFileSync, copyFileSync, rmSync } from 'fs'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'-import { readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'+import { readBuiltinBundle, readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'import { plateWorkerSource } from './scripts/lib/plateWorker.mjs'import { memoryWorkerSource } from './scripts/lib/memoryWorker.mjs'import { fileURLToPath } from 'node:url'const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(new URL('../store/agents/autonomous-grid', import.meta.url))))+const devicesBundle = JSON.stringify(readBuiltinBundle(fileURLToPath(new URL('../store/agents/devices', import.meta.url)), ['harness.json', 'AGENTS.md', 'LICENSE', 'template']))const version =process.env.ADAPTER_VERSION ||@@ -44,6 +45,7 @@ await esbuild.build({__ADAPTER_VERSION__: JSON.stringify(version),__DSH_REGISTRY__: JSON.stringify(dshRegistry),__MODEL_MANAGER_BUNDLE__: JSON.stringify(modelManagerBundle),+ __DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__PLATE_WORKER__: JSON.stringify(plateWorker),__MEMORY_WORKER__: JSON.stringify(memoryWorker),},diff --git a/cli/build.mjs b/cli/build.mjsindex 6f31b2606..159fb259c 100644--- a/cli/build.mjs+++ b/cli/build.mjs@@ -2,11 +2,12 @@ import * as esbuild from 'esbuild'import { readdirSync, statSync, readFileSync } from 'fs'import { join } from 'path'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'-import { readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'+import { readBuiltinBundle, readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'import { plateWorkerSource } from './scripts/lib/plateWorker.mjs'import { memoryWorkerSource } from './scripts/lib/memoryWorker.mjs'import { fileURLToPath } from 'node:url'const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(new URL('../store/agents/autonomous-grid', import.meta.url))))+const devicesBundle = JSON.stringify(readBuiltinBundle(fileURLToPath(new URL('../store/agents/devices', import.meta.url)), ['harness.json', 'AGENTS.md', 'LICENSE', 'template']))// Bake the version in so `node dist/cli.js version` works in the dev/per-file build too (parity with// build-bundle.mjs). The bundle build overrides this from ADAPTER_VERSION at release time.@@ -48,6 +49,7 @@ try {__ADAPTER_VERSION__: JSON.stringify(version),__DSH_REGISTRY__: JSON.stringify(dshRegistry),__MODEL_MANAGER_BUNDLE__: JSON.stringify(modelManagerBundle),+ __DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__PLATE_WORKER__: JSON.stringify(plateWorker),__MEMORY_WORKER__: JSON.stringify(memoryWorker),},diff --git a/cli/scripts/lib/modelManagerBundle.mjs b/cli/scripts/lib/modelManagerBundle.mjsindex ec34bd35e..9746b8358 100644--- a/cli/scripts/lib/modelManagerBundle.mjs+++ b/cli/scripts/lib/modelManagerBundle.mjs@@ -4,6 +4,10 @@ import { join } from 'node:path'// Ship the manager itself with the CLI. No clone, package manager, or model// download is needed to make its conversation and viewer available.export function readModelManagerBundle(root) {+ return readBuiltinBundle(root, ['harness.json', 'AGENTS.md', 'LICENSE', 'VERSIONS', 'viewer.sh', 'viewer.mjs', 'viewer', 'lib', 'toolchain', 'template', 'skills'])+}++export function readBuiltinBundle(root, paths) {const files = {}const visit = relative => {const path = join(root, relative)@@ -14,6 +18,6 @@ export function readModelManagerBundle(root) {files[relative] = { content: readFileSync(path, 'utf8'), executable: Boolean(stat.mode & 0o111) }}}- for (const path of ['harness.json', 'AGENTS.md', 'LICENSE', 'VERSIONS', 'viewer.sh', 'viewer.mjs', 'viewer', 'lib', 'toolchain', 'template', 'skills']) visit(path)+ for (const path of paths) visit(path)return files}diff --git a/cli/src/backendSocket.devices.spec.ts b/cli/src/backendSocket.devices.spec.tsnew file mode 100644index 000000000..d91ed5825--- /dev/null+++ b/cli/src/backendSocket.devices.spec.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest'+import { BackendSocket } from './backendSocket.js'++describe('Devices host ownership', () => {+ it.each(['harness_devices_list', 'harness_device_settings'])('requires sealed owner requests for %s and replies to that connection', async type => {+ const socket = new BackendSocket('fixture'), internals = socket as any+ const status = vi.fn(() => ({ attached: true, devices: [{ id: 'usb', attached: true, settings: { brightness: 80 } }] }))+ const set = vi.fn(async () => ({ ok: true }))+ socket.harnessDevices = { status: status as any, set }+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue('web')+ const clear = { type, payload: { requestId: 'one', id: 'usb', patch: { brightness: 35 } } }+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue(clear)+ const reply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({ type: `${type}_result`, payload: { __e2e: 'sealed' } })+ await internals.dispatchDown(clear, 'remote')+ expect(status).not.toHaveBeenCalled()+ const sealed = { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }+ role.mockReturnValue('device')+ await internals.dispatchDown(sealed, 'remote')+ expect(status).not.toHaveBeenCalled()+ role.mockReturnValue('web')+ await internals.dispatchDown(sealed, 'remote')+ expect(status).toHaveBeenCalled()+ expect(reply).toHaveBeenLastCalledWith('remote', `${type}_result`, 'one', expect.objectContaining(type.endsWith('list') ? { protocol: 1 } : { ok: true }))+ if (type.endsWith('settings')) expect(set).toHaveBeenCalledExactlyOnceWith('usb', { brightness: 35 })+ const local: unknown[] = []+ socket.registerLocalClient('local:tool', { sendFrame: frame => { local.push(frame); return true }, sendBinary: () => true }, { tool: true })+ await internals.dispatchDown(clear, 'local:tool')+ expect(local).toContainEqual(expect.objectContaining({ type: `${type}_result`, payload: expect.objectContaining({ requestId: 'one' }) }))+ await socket.stop()+ })+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 10896f21b..8b0e653df 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -56,6 +56,7 @@ import { opencodeMajorVersion } from './engines/opencode/version.js'import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'import { probeEngines } from './lib/engineProbe.js'import { readMachineResources } from './lib/machineResources.js'+import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'import { createHarnessResourcesReader } from './lib/harnessResources.js'import { createHarnessStorageReader } from './lib/harnessTelemetry.js'import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'@@ -436,6 +437,7 @@ function gridModelsPayload(gridName: string | null, sections: GridSection[], row}export class BackendSocket {+ harnessDevices: HarnessDevicesService | null = nullprivate readonly gridFleet = new GridFleetRpc()// The Model Manager reads the grid it runs on through the same credential-less reader as every picker// (never `grid engines`, which carries the grid credential and so wakes a sleeping grid on every tick),@@ -3403,6 +3405,17 @@ export class BackendSocket {return}+ // Physical devices belong to this machine; only its owner or loopback tools may manage them.+ case 'harness_devices_list':+ case 'harness_device_settings': {+ if (!local && this.e2ee.sessionRole(connId) !== 'web') {+ reply(type, requestId, { error: 'OWNER_REQUIRED' })+ return+ }+ reply(type, requestId, await harnessDevicesRequest(this.harnessDevices, type, payload))+ return+ }+// The colours the desktop paints its panes with, so tmux answers a TUI's OSC 10/11 with// them instead of with whatever terminal happened to attach first (lib/hostTheme.ts).case 'theme_set': {diff --git a/cli/src/cable/cableFleet.ts b/cli/src/cable/cableFleet.tsindex e1bbece30..f2b329784 100644--- a/cli/src/cable/cableFleet.ts+++ b/cli/src/cable/cableFleet.ts@@ -220,7 +220,7 @@ export class CableFleet {if (!entry) return { ok: false, error: 'That device is not plugged into this computer.' }if (!entry.status.attached) return { ok: false, error: 'That device is unplugged.' }try {- await entry.session.setSettings(patch)+ if (!await entry.session.setSettings(patch)) return { ok: false, error: 'The device did not take the change.' }return { ok: true }} catch (error) {this.host.log(`cable: ${entry.port.path} settings: ${String(error)}`)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex c7df7c916..32a166e85 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,7 +1,8 @@#!/usr/bin/env nodeimport './config/loadEnv.js'import { CompanionZoo, readCompanionIdentity, type CompanionIdentity } from './cable/companionIdentity.js'-import { MODEL_MANAGER_ID, ensureBundledModelManager } from './dsh/builtins.js'+import { MODEL_MANAGER_ID, ensureBundledDevices, ensureBundledModelManager } from './dsh/builtins.js'+import { runDevicesCommand } from './devices/client.js'import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/storeRuntime.js'import { mutateDsh } from './dsh/service.js'import { HarnessShareOwner } from './sharing/owner.js'@@ -2219,6 +2220,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {try { ensureBundledModelManager() }catch (error) { console.warn('[model-manager] Could not prepare the bundled harness:', error instanceof Error ? error.message : String(error)) }+ try { ensureBundledDevices() }+ catch (error) { console.warn('[devices] Could not prepare the bundled harness:', error instanceof Error ? error.message : String(error)) }// Grid is an add-on (`lib/gridAttach.ts`): nothing on this path installs `grid`, signs this machine in// to it or creates a grid. The first grid feature a person uses — the models picker's Set up, a local@@ -7330,6 +7333,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {log: (line) => console.log(`[device] ${line}`),})+ let devicesStatusRevision = 0const cableHost = new DaemonCableHost({// Zoo selection is visual identity; it does not require consent to watch terminal activity.// Guest identity is only a fallback while signed out, never another account's cached choice.@@ -7391,8 +7395,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The dial's swarm pick. Local-only like the two above: a tab is a thing THIS window has.swarmSelected: (swarmId) => backend.sendLocal({ type: 'dial_swarm', payload: { swarmId } }),scrolled: (phase, dy, velocity) => backend.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),- // Local-only like the three above: which desk has a dial on it is a fact about THIS computer.- dialStatus: (status) => backend.sendLocal({ type: 'dial_status', payload: status }),+ // Gestures remain local. Device inventory/settings also reach the owner's+ // other machines through the encrypted device-management event.+ dialStatus: (status) => {+ devicesStatusRevision+++ backend.sendLocal({ type: 'dial_status', payload: status })+ backend.send({ type: 'harness_devices_changed', payload: { status, revision: devicesStatusRevision } })+ },// Words spoken on the overview belong to whichever agent the window's palette picks.routeInWindow: (text, cmd) => windowRouter.ask(text, cmd),selectPassage: command => windowSelection.command(command),@@ -7404,6 +7413,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {log: (line) => console.log(`[cable] ${line}`),}, fleet)cableHostRef = cableHost+ backend.harnessDevices = {+ status: () => cableHost.currentDialStatus(),+ revision: () => devicesStatusRevision,+ set: async (id, patch) => cableRef+ ? cableRef.setSettings(id, patch)+ : { ok: false, error: 'Device service unavailable' },+ }// Anything the window said while this was still being built.cableHost.setDesk(appPaneAgents)cableHost.setSwarms(appSwarmsLatest)@@ -8817,6 +8833,13 @@ switch (cmd) {case 'autonomous-device':runAutonomousDeviceCommand(rest, env.ADAPTER_DATA_DIR, daemonPort()).then(code => { process.exitCode = code }).catch(onError)break+ case 'hardware':+ runDevicesCommand(rest, {+ port: daemonPort(),+ machineId: async () => (await runningDaemonStatus())?.machineId ?? null,+ connect: (url) => new NewCommandSocket(url),+ }).then(code => { process.exitCode = code }).catch(onError)+ breakcase 'pair': {// `harness pair <code>` pairs a browser; `harness pair <verb>` is the daemon's control interface// (pair/client.ts). No pairing code is ever one of the verbs.diff --git a/cli/src/devices/client.spec.ts b/cli/src/devices/client.spec.tsnew file mode 100644index 000000000..508026873--- /dev/null+++ b/cli/src/devices/client.spec.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from 'vitest'+import { EventEmitter } from 'node:events'+import { devicesCommand, deviceRequest, type DevicesClientDeps } from './client.js'++const snapshot = (brightness = 80) => ({ status: { devices: [{ id: 'usb', attached: true, settings: { brightness } }] } })+function fixture() {+ const request = vi.fn(async (_id: string, _type: string, _payload?: Record<string, unknown>) => snapshot() as Record<string, unknown>)+ const deps: DevicesClientDeps = {+ port: 18473, machineId: async () => 'local', connect: () => { throw new Error('No real sockets') }, request,+ fetch: vi.fn(async () => new Response(JSON.stringify({ data: { machines: [+ { machineId: 'local', name: 'Studio', status: 'running' },+ { machineId: 'remote', name: 'Office', status: 'running' },+ { machineId: 'offline', name: 'Workshop', status: 'offline' },+ { machineId: 'shared', isShared: true, status: 'running' },+ ] } }))) as typeof fetch,+ delay: async () => {},+ }+ return { deps, request }+}++describe('Devices DSH commands', () => {+ it('lists owned hosts, keeps offline presence, and reports unreachable hosts without inventing devices', async () => {+ const { deps, request } = fixture()+ request.mockRejectedValueOnce(new Error('unavailable'))+ const result = await devicesCommand(['list', '--json'], deps)+ expect(result.hosts).toMatchObject([+ { machineId: 'local', available: false, error: 'unavailable' },+ { machineId: 'remote', available: true, status: { devices: [{ id: 'usb' }] } },+ { machineId: 'offline', online: false, available: false },+ ])+ expect(request.mock.calls.map(call => call[0])).toEqual(['local', 'remote'])+ })+ it('targets only the selected host and waits for firmware confirmation', async () => {+ const { deps, request } = fixture()+ request.mockResolvedValueOnce({ ok: true, ...snapshot() }).mockResolvedValueOnce(snapshot(35))+ expect(await devicesCommand(['set', '--machine', 'remote', '--device', 'usb', '--patch', '{"brightness":35}'], deps))+ .toMatchObject({ confirmed: true, machineId: 'remote', id: 'usb', settings: { brightness: 35 } })+ expect(request.mock.calls).toEqual([+ ['remote', 'harness_device_settings', { id: 'usb', patch: { brightness: 35 } }],+ ['remote', 'harness_devices_list'],+ ])+ })+ it('does not turn acceptance into confirmation and never writes offline or shared hosts', async () => {+ const { deps, request } = fixture()+ request.mockResolvedValueOnce({ ok: true, ...snapshot() })+ const args = ['set', '--machine', 'remote', '--device', 'usb', '--patch', '{"brightness":35}']+ expect(await devicesCommand(args, deps)).toMatchObject({ accepted: true, confirmed: false })+ request.mockClear()+ for (const id of ['offline', 'shared', 'unknown']) {+ await expect(devicesCommand([...args.slice(0, 2), id, ...args.slice(3)], deps)).rejects.toThrow()+ }+ await expect(devicesCommand(['set', '--machine', 'remote', '--device', 'usb', '--patch', '{"face":466}'], deps)).rejects.toThrow()+ expect(request).not.toHaveBeenCalled()+ })+ it('waits for host selection, correlates the reply, and closes the tool socket', async () => {+ const socket = Object.assign(new EventEmitter(), { send: vi.fn(), close: vi.fn() })+ const { deps } = fixture()+ deps.connect = () => socket+ const reply = deviceRequest(deps, 'remote', 'harness_devices_list')+ socket.emit('open')+ expect(JSON.parse(socket.send.mock.calls[0]![0])).toMatchObject({ type: 'machine_select', payload: { machineId: 'remote', tool: true, localProtocolVersion: 1 } })+ socket.emit('message', JSON.stringify({ type: 'connected' }))+ const call = JSON.parse(socket.send.mock.calls[1]![0])+ socket.emit('message', JSON.stringify({ type: 'harness_devices_list_result', payload: { requestId: 'wrong', status: 'bad' } }))+ expect(socket.close).not.toHaveBeenCalled()+ socket.emit('message', JSON.stringify({ type: 'harness_devices_list_result', payload: { requestId: call.payload.requestId, ...snapshot() } }))+ expect(await reply).toEqual(snapshot())+ expect(socket.close).toHaveBeenCalledOnce()+ })+})diff --git a/cli/src/devices/client.ts b/cli/src/devices/client.tsnew file mode 100644index 000000000..05fd20efa--- /dev/null+++ b/cli/src/devices/client.ts@@ -0,0 +1,135 @@+/** Devices DSH tools use the same owned-machine bridge as Desktop. No serial or credential access. */+import { randomUUID } from 'node:crypto'+import type { PairSocket } from '../pair/client.js'+import { deviceSettingsPatchSchema } from '../lib/harnessDevices.js'++export interface DevicesClientDeps {+ port: number+ machineId(): Promise<string | null>+ connect(url: string): PairSocket+ fetch?: typeof fetch+ request?: (machineId: string, type: string, payload?: Record<string, unknown>) => Promise<Record<string, unknown>>+ delay?: (ms: number) => Promise<void>+}++export function deviceRequest(deps: DevicesClientDeps, machineId: string, type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {+ return new Promise((resolve, reject) => {+ const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`)+ const requestId = randomUUID()+ let settled = false, sent = false+ const finish = (error: Error | null, reply?: Record<string, unknown>): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ try { socket.close() } catch { /* already closed */ }+ if (error) reject(error); else resolve(reply!)+ }+ const timer = setTimeout(() => finish(new Error('This computer did not answer in time.')), 12_000)+ socket.on('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, tool: true } })))+ socket.on('error', error => finish(error))+ socket.on('close', code => finish(new Error(code === 4404 ? 'Link this computer in Machines first.' : 'The computer disconnected.')))+ socket.on('message', data => {+ let frame: { type?: string; payload?: Record<string, unknown> }+ try { frame = JSON.parse(data.toString()) } catch { return }+ if (frame.type === 'connected' && !sent) {+ sent = true+ socket.send(JSON.stringify({ type, payload: { ...payload, requestId } }))+ }+ if (frame.type === `${type}_result` && frame.payload?.requestId === requestId) {+ const { requestId: _id, ...reply } = frame.payload+ finish(null, reply)+ }+ })+ })+}++export const DEVICES_USAGE = `harness hardware — your Harness hardware across computers+ list [--json] read owned computers and devices+ set --machine ID --device ID --patch JSON [--json] change only the supplied settings+Offline computers never receive queued changes. A write is complete only when confirmed.`++interface Host { machineId: string; name: string; online: boolean }+async function ownedHosts(deps: DevicesClientDeps): Promise<Host[]> {+ const localId = await deps.machineId()+ if (!localId) throw new Error('Start Harness on this computer first.')+ const response = await (deps.fetch ?? fetch)(`http://127.0.0.1:${deps.port}/api/machines`, {+ headers: { 'x-adapter-local': '1' }, signal: AbortSignal.timeout(8000),+ })+ if (!response.ok) throw new Error('Could not read the account’s computers. Sign in and try again.')+ const body = await response.json() as { data?: { machines?: Record<string, unknown>[] }; machines?: Record<string, unknown>[] }+ const rows = body.data?.machines ?? body.machines+ if (!Array.isArray(rows)) throw new Error('Harness returned an invalid computer list.')+ const hosts = rows.filter(row => typeof row.machineId === 'string' && !row.isShared).map(row => ({+ machineId: row.machineId as string,+ name: String(row.name || row.hostname || row.machineId),+ online: row.machineId === localId || row.status === 'running',+ }))+ if (!hosts.some(host => host.machineId === localId)) hosts.unshift({ machineId: localId, name: 'This computer', online: true })+ return hosts+}++function observed(reply: Record<string, unknown>, id: string): Record<string, unknown> | undefined {+ const status = reply.status as { devices?: Record<string, unknown>[]; id?: string } | undefined+ return (status?.devices ?? (status ? [status] : [])).find(device => device.id === id)+}++/** Separate from printing so the exact routing and confirmation path is testable. */+export async function devicesCommand(argv: string[], deps: DevicesClientDeps): Promise<Record<string, unknown>> {+ const words = argv.filter(word => word !== '--json')+ const command = words.shift() ?? 'list'+ if (command === 'help' || command === '--help') return { help: DEVICES_USAGE }+ if (command !== 'list' && command !== 'set') throw new Error(DEVICES_USAGE)+ const options: Record<string, string> = {}+ if (command === 'list' && words.length) throw new Error(DEVICES_USAGE)+ for (let i = 0; i < words.length; i += 2) {+ const key = words[i]!+ if (!['--machine', '--device', '--patch'].includes(key) || !words[i + 1] || key in options) throw new Error(DEVICES_USAGE)+ options[key] = words[i + 1]!+ }+ let patch: Record<string, unknown> | undefined+ if (command === 'set') {+ if (!options['--machine'] || !options['--device'] || !options['--patch']) throw new Error(DEVICES_USAGE)+ patch = deviceSettingsPatchSchema.parse(JSON.parse(options['--patch']))+ }+ const hosts = await ownedHosts(deps)+ const request = deps.request ?? ((id, type, payload) => deviceRequest(deps, id, type, payload))+ if (command === 'list') {+ return { hosts: await Promise.all(hosts.map(async host => {+ if (!host.online) return { ...host, available: false }+ try {+ const reply = await request(host.machineId, 'harness_devices_list')+ return { ...host, available: !reply.error, ...reply }+ } catch (error) { return { ...host, available: false, error: error instanceof Error ? error.message : 'Unavailable' } }+ })) }+ }+ const host = hosts.find(host => host.machineId === options['--machine'])+ if (!host) throw new Error('That computer is not owned by this account.')+ if (!host.online) throw new Error('That computer is offline. No change was sent.')+ const id = options['--device']!+ let reply = await request(host.machineId, 'harness_device_settings', { id, patch })+ if (reply.error || reply.ok !== true) return { ...reply, confirmed: false }+ const delay = deps.delay ?? (ms => new Promise(resolve => setTimeout(resolve, ms)))+ for (let attempt = 0; attempt < 13; attempt++) {+ const device = observed(reply, id)+ const values = device?.settings as Record<string, unknown> | undefined+ if (device?.attached === true && !device.updating && values && Object.entries(patch!).every(([key, value]) => values[key] === value)) {+ return { ok: true, confirmed: true, machineId: host.machineId, id, settings: values }+ }+ if (reply.error || device?.attached === false || device?.updating || attempt === 12) break+ await delay(500)+ reply = await request(host.machineId, 'harness_devices_list')+ }+ return { ok: false, accepted: true, confirmed: false, machineId: host.machineId, id,+ error: 'The device has not confirmed the change. Refresh Devices before trying again.' }+}++export async function runDevicesCommand(argv: string[], deps: DevicesClientDeps): Promise<number> {+ try {+ const result = await devicesCommand(argv, deps)+ console.log(result.help ?? JSON.stringify(result, null, argv.includes('--json') ? undefined : 2))+ return result.error ? 1 : 0+ } catch (error) {+ console.log(JSON.stringify({ error: error instanceof Error ? error.message : 'Device request failed.', confirmed: false }))+ return 1+ }+}diff --git a/cli/src/dsh/builtins.spec.ts b/cli/src/dsh/builtins.spec.tsindex 4fefb373c..ecadad5ca 100644--- a/cli/src/dsh/builtins.spec.ts+++ b/cli/src/dsh/builtins.spec.ts@@ -3,12 +3,25 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fsimport { tmpdir } from 'node:os'import { join } from 'node:path'import { env } from '../config/env.js'-import { ensureBundledModelManager, MODEL_MANAGER_ID } from './builtins.js'+import { ensureBundledDevices, ensureBundledModelManager, DEVICES_HARNESS_ID, MODEL_MANAGER_ID } from './builtins.js'+import { dshListRows } from './wire.js'import { installedDsh, invalidateInstalledDsh, upsertInstalledRecord } from './installed.js'import { lockDsh } from './lock.js'let root: stringlet original: string+it('ships Devices as an unlisted DSH with the shared daemon commands and reusable workspace', () => {+ const files = Object.fromEntries(['harness.json', 'AGENTS.md', 'template/devices.json'].map(path => [path,+ { content: readFileSync(new URL(`../../../store/agents/devices/${path}`, import.meta.url), 'utf8'), executable: false }]))+ expect(ensureBundledDevices(files)).toBe(true)+ const installed = installedDsh(DEVICES_HARNESS_ID)!+ expect(installed.manifest.workspace?.marker).toBe('devices.json')+ expect(installed.manifest.agent?.env?.DSH_PERMISSION_MODE).toBe('ask')+ expect(dshListRows([installed], [])).toEqual([])+ expect(files['AGENTS.md']!.content).toContain('harness hardware list --json')+ expect(ensureBundledDevices(files)).toBe(true)+ expect(installedDsh(DEVICES_HARNESS_ID)?.dir).toBe(installed.dir)+})beforeEach(() => {root = mkdtempSync(join(tmpdir(), 'model-manager-bundle-'))original = env.DSH_DIRdiff --git a/cli/src/dsh/builtins.ts b/cli/src/dsh/builtins.tsindex 470fcd628..f5034b426 100644--- a/cli/src/dsh/builtins.ts+++ b/cli/src/dsh/builtins.ts@@ -6,7 +6,10 @@ import { lockDsh } from './lock.js'import { readDshManifest } from './manifest.js'declare const __MODEL_MANAGER_BUNDLE__: string+declare const __DEVICES_BUNDLE__: stringexport const MODEL_MANAGER_ID = 'autonomous/autonomous-grid'+export const DEVICES_HARNESS_ID = 'autonomous/devices'+export const DEVICES_BUILTIN_SOURCE = 'builtin:devices'export type BundledFiles = Record<string, { content: string; executable: boolean }>/** Install the trusted, release-bundled harness. Runtime provisioning remains@@ -18,6 +21,13 @@ export function ensureBundledModelManager(files?: BundledFiles): boolean {return installBuiltin({ id: MODEL_MANAGER_ID, source: 'builtin:model-manager', folder: 'model-manager', files, what: 'Model Manager' })}+/** An unlisted first-party DSH. Its viewer is native; its agent uses the same daemon API. */+export function ensureBundledDevices(files?: BundledFiles): boolean {+ files ??= typeof __DEVICES_BUNDLE__ === 'string' ? JSON.parse(__DEVICES_BUNDLE__) as BundledFiles : undefined+ if (!files?.['harness.json']) return false+ return installBuiltin({ id: DEVICES_HARNESS_ID, source: DEVICES_BUILTIN_SOURCE, folder: 'devices', files, what: 'Devices' })+}+/** The pair harness (pair/pairHarness.ts): generated on this machine, never listed in the Store or the picker. */export const PAIR_BUILTIN_SOURCE = 'builtin:pair'@@ -27,9 +37,9 @@ export function ensureBuiltinPair(id: string, files: BundledFiles): boolean {return installBuiltin({ id, source: PAIR_BUILTIN_SOURCE, folder: 'pair', files, what: 'pair harness' })}-/** A built-in that is the daemon's own and no person's to pick: the pair harness. */+/** Built-ins opened through their own product entry points, absent from the public picker. */export function isHiddenBuiltin(record: { source?: string | null }): boolean {- return record.source === PAIR_BUILTIN_SOURCE+ return record.source === PAIR_BUILTIN_SOURCE || record.source === DEVICES_BUILTIN_SOURCE}/** Materialize `files` under `.bundled/<folder>/<revision>` and point the index at it. Idempotent per revision. */diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex 35cd1dcb5..ec5af5f43 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -209,6 +209,23 @@ describe('e2ee core — codes + fingerprint + classification', () => {requestId: 'models-1', models: [{ id: 'runtime-v1:s1:codex:gpt@high' }],})})++ it('encrypts device discovery, settings, replies and inventory broadcasts', () => {+ for (const type of ['harness_devices_list', 'harness_device_settings']) {+ expect(C.isEncryptedDownType(type)).toBe(true)+ expect(C.isEncryptedRpcResultType(`${type}_result`)).toBe(true)+ }+ expect(C.isEncryptedUpType('harness_devices_changed')).toBe(true)+ const key = seeded(31)(32)+ const patch = { id: 'device-1', patch: { brightness: 40 } }+ const request = C.wrapPayload(key, 'p', 1, 'harness_device_settings', undefined, patch)+ expect(request).not.toHaveProperty('patch')+ expect(C.unwrapPayload(key, request.__e2e, 'harness_device_settings', undefined)).toEqual(patch)+ const inventory = { revision: 2, status: { devices: [{ id: 'device-1', attached: true }] } }+ const event = C.wrapPayload(key, 'g', 2, 'harness_devices_changed', undefined, inventory, 'ab12cd34')+ expect(event).not.toHaveProperty('status')+ expect(C.unwrapPayload(key, event.__e2e, 'harness_devices_changed', undefined)).toEqual(inventory)+ })})/**@@ -224,6 +241,6 @@ describe('e2ee core — interop keystone', () => {it('core.ts still hashes to the pinned value shared with the other implementations', () => {const here = dirname(fileURLToPath(import.meta.url))const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')- expect(actual).toBe('122eda9ad44db16a1c983d9951340e17826fe3921202036bf2030f3a9116e80f')+ expect(actual).toBe('bf8c3f18c8c3eb4cf675e2027e19fd23523bb691e47045f057ff5725af45a685')})})diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex a40a1e052..b01541f76 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -337,12 +337,14 @@ export function isWrapped(payload: unknown): payload is WrappedPayload {/** `up` events (adapter→web, group key) whose payload carries user content. */export const ENCRYPTED_UP_TYPES = new Set<string>([+ 'harness_devices_changed','user_message', 'text_delta', 'thinking_delta', 'thinking_title', 'tool_start', 'tool_end','turn_started', 'turn_ended', 'done', 'context_compact', 'turn_summary', 'turn_summary_pending','agent_created', 'agent_synced', 'agent_renamed', 'agent_deleted',])/** RPC replies (`<x>_result`) whose payload is encrypted ONLY when the requester has a session. */export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([+ 'harness_devices_list_result', 'harness_device_settings_result','session_get_result', 'sessions_list_result', 'agents_list_result', 'models_list_result','agent_files_result', 'agent_read_file_result', 'agent_update_result', 'agent_delete_result','e2ee_pairings_list_result', 'e2ee_pairing_unpair_result',@@ -370,6 +372,7 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([])/** Client→adapter frames that carry or can trigger adapter-local user data. */export const ENCRYPTED_DOWN_TYPES = new Set<string>([+ 'harness_devices_list', 'harness_device_settings','message',// An AskUserQuestion answer is user content, so the firmware wraps it (e2ee_manager.c). Leaving it out// of this set did NOT fail loudly: unwrapDown was simply never called, the payload stayed the rawdiff --git a/cli/src/lib/harnessDevices.spec.ts b/cli/src/lib/harnessDevices.spec.tsnew file mode 100644index 000000000..48f6dcd02--- /dev/null+++ b/cli/src/lib/harnessDevices.spec.ts@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from 'vitest'+import { harnessDevicesRequest, type HarnessDevicesService } from './harnessDevices.js'+import type { DialStatus, DeviceSettings } from '../cable/cableSession.js'+import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'+import { ENCRYPTED_UP_TYPES } from './e2ee/core.js'++const settings: DeviceSettings = { brightness: 80, muted: false, quiet: false, character: 2,+ face: 466, round: true, voiceLang: 'en', scrollReversed: false, straightTitle: true, focusFace: false }+describe('owner device management', () => {+ const fixture = () => {+ const devices: DialStatus[] = [+ { id: 'usb-a', attached: true, settings },+ { id: 'usb-b', attached: true, settings },+ { id: 'offline', attached: false, settings },+ { id: 'updating', attached: true, settings, updating: 'next' },+ ]+ const set = vi.fn(async () => ({ ok: true }))+ const service: HarnessDevicesService = { status: () => ({ attached: true, devices }), revision: () => 4, set }+ return { service, set }+ }+ it('reads the whole host and sends a sparse patch only to the named device', async () => {+ const { service, set } = fixture()+ expect(await harnessDevicesRequest(service, 'harness_devices_list', {})).toMatchObject({ protocol: 1, revision: 4, status: { devices: expect.any(Array) } })+ const reply = await harnessDevicesRequest(service, 'harness_device_settings', { id: 'usb-b', patch: { brightness: 35 } })+ expect(set).toHaveBeenCalledExactlyOnceWith('usb-b', { brightness: 35 })+ expect(reply).toMatchObject({ ok: true, status: { devices: [{ settings: { brightness: 80 } }, { settings: { brightness: 80 } }, {}, {}] } })+ })+ it('refuses missing, disconnected, updating and invalid targets without a write', async () => {+ const { service, set } = fixture()+ for (const id of ['missing', 'offline']) expect(await harnessDevicesRequest(service, 'harness_device_settings', { id, patch: { muted: true } })).toMatchObject({ error: 'DEVICE_OFFLINE' })+ expect(await harnessDevicesRequest(service, 'harness_device_settings', { id: 'updating', patch: { muted: true } })).toMatchObject({ error: 'DEVICE_UPDATING' })+ for (const patch of [{ brightness: 101 }, { id: 'usb-a' }, { face: 720 }, {}, { muted: 'true' }]) {+ expect(await harnessDevicesRequest(service, 'harness_device_settings', { id: 'usb-b', patch })).toMatchObject({ error: 'BAD_DEVICE_SETTINGS' })+ }+ expect(set).not.toHaveBeenCalled()+ })+ it('does not report a failed cable delivery as success', async () => {+ const { service, set } = fixture()+ set.mockResolvedValue({ ok: false })+ expect(await harnessDevicesRequest(service, 'harness_device_settings', { id: 'usb-a', patch: { muted: true } })).toMatchObject({ error: 'DEVICE_WRITE_FAILED' })+ })+ it('encrypts requests, replies and device snapshots over remote relays', () => {+ for (const type of ['harness_devices_list', 'harness_device_settings']) {+ expect(encryptDownFrame(type)).toBe(true)+ expect(encryptRpcResult(`${type}_result`)).toBe(true)+ }+ expect(ENCRYPTED_UP_TYPES.has('harness_devices_changed')).toBe(true)+ })+})diff --git a/cli/src/lib/harnessDevices.ts b/cli/src/lib/harnessDevices.tsnew file mode 100644index 000000000..2bed87078--- /dev/null+++ b/cli/src/lib/harnessDevices.ts@@ -0,0 +1,41 @@+import { z } from 'zod'+import type { DeviceSettingsPatch, DialStatus } from '../cable/cableSession.js'++export interface HarnessDevicesService {+ status(): DialStatus+ revision?(): number+ set(id: string, patch: DeviceSettingsPatch): Promise<{ ok: boolean; error?: string }>+}++export const deviceSettingsPatchSchema = z.object({+ brightness: z.number().int().min(0).max(100).optional(),+ muted: z.boolean().optional(),+ quiet: z.boolean().optional(),+ scrollReversed: z.boolean().optional(),+ voiceLang: z.string().regex(/^[a-z]{2}(?:-[A-Z]{2})?$/).optional(),+ character: z.number().int().min(0).max(255).optional(),+ straightTitle: z.boolean().optional(),+ focusFace: z.boolean().optional(),+ followCompanion: z.boolean().optional(),+}).strict().refine(value => Object.keys(value).length > 0)+const change = z.object({ id: z.string().min(1).max(256), patch: deviceSettingsPatchSchema })++/** The authenticated connection selects the host; payloads only select its USB device. */+export async function harnessDevicesRequest(+ service: HarnessDevicesService | null, type: string, payload: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ if (!service) return { error: 'UNSUPPORTED' }+ if (type === 'harness_devices_list') return { protocol: 1, revision: service.revision?.() ?? 0, status: service.status() }+ const parsed = change.safeParse({ id: payload.id, patch: payload.patch })+ if (!parsed.success) return { error: 'BAD_DEVICE_SETTINGS' }+ const snapshot = service.status()+ const device = (snapshot.devices ?? [snapshot]).find(item => item.id === parsed.data.id)+ if (!device?.attached) return { error: 'DEVICE_OFFLINE' }+ if (device.updating) return { error: 'DEVICE_UPDATING' }+ if (!device.settings) return { error: 'DEVICE_NOT_READY' }+ const sent = await service.set(parsed.data.id, parsed.data.patch)+ if (!sent.ok) return { error: 'DEVICE_WRITE_FAILED' }+ // Acceptance is not firmware acknowledgment. The subsequent status event+ // reports what the device actually holds, including a refused setting.+ return { ok: true, revision: service.revision?.() ?? 0, status: service.status() }+}diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex 701bf5d29..3a19d6e70 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -215,6 +215,32 @@ describe('local CLI WebSocket', () => {expect(backend.frames).toEqual([])ws.close()})+ it('relays addressed device commands without sending legacy writes to the local cable', async () => {+ const backend = new FakeBackend(), localSettings = vi.fn(), relayed: Frame[] = []+ const relayPool = {+ acquire: async (_id: string, _env: string, _select: Frame, sink: LocalClientSink) => {+ sink.sendFrame({ type: 'connected', payload: { machineId: 'remote', e2ee: false } })+ return { send: async (frame: Frame) => { relayed.push(frame) }, sendBinary: async () => {}, detach: () => {} }+ },+ }+ const ws = new WebSocket(await start(backend, {+ autonomousEnv: 'test', onDialSettings: localSettings,+ relayPool: relayPool as unknown as NonNullable<LocalWsServerOptions['relayPool']>,+ }))+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: 'remote', localProtocolVersion: 1 } }))+ await connected+ ws.send(JSON.stringify({ type: 'dial_settings', payload: { id: 'same-usb', brightness: 90 } }))+ const addressed = { type: 'harness_device_settings', payload: { id: 'same-usb', patch: { brightness: 35 }, requestId: 'one' } }+ ws.send(JSON.stringify(addressed))+ await vi.waitFor(() => expect(relayed).toContainEqual(addressed))+ expect(localSettings).not.toHaveBeenCalled()+ expect(backend.frames).toEqual([])+ expect(relayed).toHaveLength(1)+ ws.close()+ })+it('accepts loopback, selects the exact machine, and routes JSON plus HTRL binary', async () => {const backend = new FakeBackend()const url = await start(backend)diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 5d370b89e..310f421e5 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -715,6 +715,9 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO// forwarded: a robot plugged into this computer is nothing a remote machine can act on, and the// reply is the ordinary `dial_status` the device's own answer produces.if (parsed?.type === 'dial_settings') {+ // Legacy settings are only for this desk. Remote management uses the+ // encrypted harness_device_settings RPC, dispatched by the host.+ if (relay || boundMachineId !== options.machineId) returnconst payload = (parsed.payload ?? {}) as Record<string, unknown>const id = typeof payload.id === 'string' ? payload.id : ''options.onDialSettings?.(id, payload)diff --git a/desktop/assets/devices/README.md b/desktop/assets/devices/README.mdnew file mode 100644index 000000000..912c1e9a9--- /dev/null+++ b/desktop/assets/devices/README.md@@ -0,0 +1,12 @@+# Device photography++Original product photography from https://www.autonomous.ai/harness-device,+retrieved 2026-10-01. These are the existing Harness product visuals, not+representations of a separate Pro enclosure or a connected device's live display.++- `harness-front.webp`: https://cdn.autonomous.ai/development/ecm/260924/1%281%29.webp+- `harness-side.webp`: https://cdn.autonomous.ai/development/ecm/260924/2%281%29.webp+- `harness-desk.webp`: https://cdn.autonomous.ai/development/ecm/260924/b3-1-new.webp++Bundled for offline device management. Presentation crops happen in+`DeviceArtwork`; the original images are unchanged.diff --git a/desktop/assets/devices/harness-desk.webp b/desktop/assets/devices/harness-desk.webpnew file mode 100644index 000000000..635723635Binary files /dev/null and b/desktop/assets/devices/harness-desk.webp differdiff --git a/desktop/assets/devices/harness-front.webp b/desktop/assets/devices/harness-front.webpnew file mode 100644index 000000000..ec11dd5c4Binary files /dev/null and b/desktop/assets/devices/harness-front.webp differdiff --git a/desktop/assets/devices/harness-side.webp b/desktop/assets/devices/harness-side.webpnew file mode 100644index 000000000..e24f5ac35Binary files /dev/null and b/desktop/assets/devices/harness-side.webp differdiff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.mdindex 951420a21..da642c2c2 100644--- a/desktop/design/desktop-ui-migration.md+++ b/desktop/design/desktop-ui-migration.md@@ -459,6 +459,75 @@ unmerged.[narrow light](../../docs/research/2026-10-01-session-close/light-2.0x.png).Live native interaction and VoiceOver are not claimed by these widget renders.+### Experimental Devices DSH, 2026-10-01++- Devices is an account-scoped experiment, off by default. After the server+ acknowledges opt-in, navigation reads Search → Devices → Harness Store in+ AppKit and Flutter. Clicking Devices opens the bundled `autonomous/devices`+ DSH: the native dashboard on the left and an ordinary agent terminal on the+ right, using the shared pane layout, resizing, focus and terminal controllers.+ Restoring the tab recovers that conversation after the experimental gate loads.+ Turning the experiment off closes its workspace and removes history entries.+ Older servers leave Devices unavailable without breaking existing experiments.+- The DSH is bundled in the CLI and unlisted in the Store and picker. It chooses+ an installed Codex, Claude Code or OpenCode engine, preserves creation receipts+ after a lost response, waits for existing agent discovery before creating, and+ reuses/resumes its conversation. Opening it does not submit an unsolicited+ prompt. Its `harness hardware list/set` tools use the same device RPCs as the+ dashboard; the existing `harness devices` account-key commands remain intact.+- The list spans owned, linked computers. Each card names its host. Settings+ travel through that computer's authenticated daemon, with encrypted requests,+ results and device-status events. Duplicate USB ids on different computers+ stay separate. Shared harness access does not grant device control. Offline+ computers and unsupported daemons keep last readings visible with controls+ disabled; edits are never queued for later. Gestures remain local to the desk.+- Original [product photography](https://www.autonomous.ai/harness-device), shared+ settings rows and light/dark surfaces frame the library, selected device,+ USB setup and empty-state Shop entry. Names and model labels are saved locally+ per account. Firmware does not identify a retail SKU; Harness/Pro is explicitly+ chosen during setup, never inferred from display dimensions. The library adds+ no wireless pairing, battery reading or invented Pro capability.+- Settings follow production firmware on `origin/main`: brightness, sound,+ reverse scrolling and voice language, with one Focus face and room for future+ faces. Sparse writes name both host and device. The UI and agent tools wait for+ reported settings; acceptance alone is not firmware confirmation. Disconnects,+ firmware updates, stale responses, account changes and errors cannot complete+ an unrelated save.+- Combined the useful behavior from `ab-mac-3` in the read-only `brave-spruce`+ worktree: platform/server gating, account-transition cleanup, retained offline+ readings, fresh-settings requirements after reconnect, firmware-update handling,+ native icon tint and the disposable interactive review controls. Product photos+ and this worktree's dashboard design remain the shared presentation.+- Validation: **168 unique desktop tests** across the regression and focused+ follow-up runs; **76 CLI tests** (device service, DSH tools/package, ownership,+ cable fleet and local/remote WebSocket routing); **7 backend settings tests**.+ Scoped Dart analysis, CLI/backend type checking, development and release CLI+ builds, and the icon audit pass. Repeated selections are not added to these+ counts. The final native macOS integration test passes on Apple Silicon's+ Impeller renderer, using five sample devices across three computers.+- Native captures: [light DSH](../../docs/research/2026-10-01-devices/light-devices-dsh.png),+ [dark DSH](../../docs/research/2026-10-01-devices/dark-devices-dsh.png), and+ [offline host](../../docs/research/2026-10-01-devices/offline-devices-dsh.png).+ Real-font widget coverage also includes the [empty state](../../docs/research/2026-10-01-devices/light-empty.png)+ and [narrow settings at 200% text](../../docs/research/2026-10-01-devices/narrow-enlarged.png).+ All hardware, accounts and conversation content in the review are fixtures.+ The native test injects the titlebar method-channel action; it does not prove+ physical AppKit keyboard/IME interaction, real USB hardware, live multi-machine+ operation or VoiceOver. Those remain unverified.+- `scripts/build-devices-review.sh` produces a separate `Devices Review.app`+ with sample-data controls, then rebuilds `lib/main.dart` for the regular app.+ Both builds and their signature verification passed; the combined review app+ and the light/dark DSH captures were opened for review.+ The review entrypoint requires both `HARNESS_TEST=true` and+ `DEVICES_REVIEW=true` in a debug build. No installed CLI, daemon or production+ service is changed by the review.+- After integrating current main for the PR, **212 desktop regression tests**,+ **4,352 native titlebar checks**, backend settings tests, scoped Dart analysis,+ TypeScript checks, the regular signed macOS build, release CLI bundle, package+ conformance and Store catalog validation pass. The native checks exercise the+ hidden default, opted-in ordering and action, modal blocking and disabling.+ Added the package README and refreshed the protocol checksum with explicit+ encrypted-device request/event coverage after the full CLI suite found them.### Harness Monitor and resource footer, 2026-10-01diff --git a/desktop/integration_test/devices_native_test.dart b/desktop/integration_test/devices_native_test.dartnew file mode 100644index 000000000..e1baa979e--- /dev/null+++ b/desktop/integration_test/devices_native_test.dart@@ -0,0 +1,139 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/devices/devices_screen.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/settings/experimental_features.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/theme/color_palette.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:integration_test/integration_test.dart';+import 'package:window_manager/window_manager.dart';++import '../test/keymap_runtime_test.dart' show native;+import '../tool/devices_preview.dart';++void main() {+ if (!kUnderTest) throw StateError('Use FLUTTER_TEST=1 with this fixture.');+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;+ setUpAll(() async {+ await windowManager.ensureInitialized();+ await windowManager.setSize(const Size(1440, 1040));+ await windowManager.show();+ await windowManager.focus();+ });+ testWidgets(+ 'Devices opens its native DSH, routes remote edits, and renders offline settings',+ (tester) async {+ final app = DevicesReviewApp();+ await app.prepare();+ final projects = SwarmProjectStore();+ final boundary = GlobalKey();+ Future<void> mount(Brightness brightness) async {+ grid.AppTheme.palette.value = brightness == Brightness.light+ ? HarnessPalette.paper+ : HarnessPalette.graphite;+ grid.AppTheme.brightness.value = brightness;+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (_, child) => grid.BrightnessScope(child: child!),+ home: SwarmScreen(+ notifier: app,+ nativeTabs: true,+ projectStore: projects,+ ),+ ),+ ),+ );+ final context = tester.element(find.byType(DevicesScreen));+ for (final art in ['front', 'side', 'desk']) {+ await precacheImage(+ AssetImage('assets/devices/harness-$art.webp'),+ context,+ );+ }+ await tester.pumpAndSettle();+ }++ Future<void> capture(String name) async {+ final directory = Platform.environment['HARNESS_DEVICES_CAPTURE_DIR'];+ if (directory == null) return;+ final image =+ await (boundary.currentContext!.findRenderObject()+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 1);+ try {+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(directory).create(recursive: true);+ await File('$directory/$name.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ } finally {+ image.dispose();+ }+ }++ await mount(Brightness.light);+ await native(tester, 'devices');+ await tester.pumpAndSettle();+ expect(app.activeSwarm.panes.where((p) => p.isDevices), hasLength(1));+ expect(+ app.activeSwarm.panes.where((p) => p.agentId == 'review-devices'),+ hasLength(1),+ );+ final controller = tester+ .widget<DevicesScreen>(find.byType(DevicesScreen))+ .controller;+ expect(controller.devices, hasLength(5));+ expect(controller.devices.map((d) => d.machineId).toSet(), hasLength(3));+ await capture('light-devices-dsh');+ final remote = controller.devices.firstWhere(+ (d) => d.machineId == 'office-mac',+ );+ final remoteCard = find.byKey(ValueKey('device-card-${remote.key}'));+ await tester.ensureVisible(remoteCard);+ await tester.tap(remoteCard);+ await tester.pumpAndSettle();+ final sound = find.byKey(ValueKey('devices-sound-${remote.key}'));+ await tester.ensureVisible(sound);+ await tester.tap(sound);+ await tester.pump(const Duration(milliseconds: 400));+ await tester.pumpAndSettle();+ expect(app.writes.single.$1, 'office-mac');+ expect(app.writes.single.$2, remote.status.id);+ expect(controller.device(remote.key)!.status.settings!.muted, isFalse);+ expect(controller.saving(remote.key), isFalse);+ final offline = controller.devices.firstWhere(+ (d) => d.machineId == 'workshop-pc',+ );+ final offlineCard = find.byKey(ValueKey('device-card-${offline.key}'));+ await tester.ensureVisible(offlineCard);+ await tester.tap(offlineCard);+ await tester.pumpAndSettle();+ expect(controller.device(offline.key)!.canEdit, isFalse);+ expect(controller.device(offline.key)!.status.settings, isNotNull);+ await capture('offline-devices-dsh');+ await mount(Brightness.dark);+ await tester.ensureVisible(find.byKey(const Key('devices-add')));+ await tester.pumpAndSettle();+ await capture('dark-devices-dsh');+ await app.experimentalFeatures.set(ExperimentalFeature.devicesTab, false);+ await tester.pumpAndSettle();+ await native(tester, 'devices');+ expect(app.swarms.any((tab) => tab.isDevices), isFalse);+ expect(find.byType(DevicesScreen), findsNothing);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ projects.dispose();+ app.dispose();+ },+ );+}diff --git a/desktop/lib/devices/device_artwork.dart b/desktop/lib/devices/device_artwork.dartnew file mode 100644index 000000000..11a6b1463--- /dev/null+++ b/desktop/lib/devices/device_artwork.dart@@ -0,0 +1,35 @@+import 'package:flutter/material.dart';++/// Product photography from autonomous.ai/harness-device. Bundled so the+/// library remains useful when the computer is offline.+class DeviceArtwork extends StatelessWidget {+ const DeviceArtwork({+ super.key,+ this.desk = false,+ this.side = false,+ this.closeUp = false,+ });+ final bool desk, side, closeUp;++ @override+ Widget build(BuildContext context) => ExcludeSemantics(+ child: ClipRect(+ child: Transform.scale(+ scale: closeUp ? 1.85 : 1,+ alignment: const Alignment(-.22, .12),+ child: Image.asset(+ 'assets/devices/harness-${desk+ ? 'desk'+ : side+ ? 'side'+ : 'front'}.webp',+ fit: BoxFit.cover,+ width: double.infinity,+ height: double.infinity,+ alignment: const Alignment(-.22, .12),+ filterQuality: FilterQuality.medium,+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/devices/device_hosts.dart b/desktop/lib/devices/device_hosts.dartnew file mode 100644index 000000000..fcfc77ee9--- /dev/null+++ b/desktop/lib/devices/device_hosts.dart@@ -0,0 +1,105 @@+import 'package:flutter/foundation.dart';++import '../state/dial_status.dart';++/// A host is an owned machine, not a shared harness or a caller-supplied route.+class DeviceHost {+ const DeviceHost({+ required this.id,+ required this.name,+ required this.online,+ this.local = false,+ this.available = false,+ this.status = DialStatus.none,+ this.error,+ this.revision,+ });+ final String id, name;+ final bool local, online, available;+ final DialStatus status;+ final String? error;+ final int? revision;+ List<DialStatus> get devices => status.devices.isNotEmpty+ ? status.devices+ : status.attached || status.settings != null+ ? [status]+ : const [];+}++/// Isolated from workspace repaint notifications and cleared on account changes.+class DeviceHosts extends ChangeNotifier {+ final _hosts = <String, DeviceHost>{};+ List<DeviceHost> get hosts => List.unmodifiable(_hosts.values);+ DeviceHost? host(String id) => _hosts[id];++ void reconcile(Iterable<DeviceHost> inventory) {+ final ids = <String>{};+ var changed = false;+ for (final item in inventory) {+ ids.add(item.id);+ final old = _hosts[item.id];+ if (old != null &&+ old.name == item.name &&+ old.local == item.local &&+ old.online == item.online &&+ (item.error == null || old.error == item.error)) {+ continue;+ }+ _hosts[item.id] = DeviceHost(+ id: item.id,+ name: item.name,+ local: item.local,+ online: item.online,+ available: old?.online == true && item.online && old!.available,+ status: old?.status ?? DialStatus.none,+ error: item.error,+ revision: old?.online == true && item.online ? old?.revision : null,+ );+ changed = true;+ }+ final removed = _hosts.keys.where((id) => !ids.contains(id)).toList();+ for (final id in removed) {+ _hosts.remove(id);+ }+ if (changed || removed.isNotEmpty) notifyListeners();+ }++ void receive(String id, DialStatus status, {int? revision}) {+ final old = _hosts[id];+ if (old == null || !old.online) return;+ if (revision != null && old.revision != null && revision < old.revision!) {+ return;+ }+ _hosts[id] = DeviceHost(+ id: id,+ name: old.name,+ local: old.local,+ online: true,+ available: true,+ status: status,+ revision: revision ?? old.revision,+ );+ notifyListeners();+ }++ void failed(String id, String message) {+ final old = _hosts[id];+ if (old == null) return;+ _hosts[id] = DeviceHost(+ id: id,+ name: old.name,+ local: old.local,+ online: old.online,+ available: false,+ status: old.status,+ error: message,+ revision: old.revision,+ );+ notifyListeners();+ }++ void clear() {+ _hosts.clear();+ notifyListeners();+ }+}diff --git a/desktop/lib/devices/device_settings.dart b/desktop/lib/devices/device_settings.dartnew file mode 100644index 000000000..1f6e81399--- /dev/null+++ b/desktop/lib/devices/device_settings.dart@@ -0,0 +1,299 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/app_select_field.dart';+import '../shared/widgets/setting_row.dart';+import '../widgets/desktop_chrome.dart';+import 'devices_controller.dart';++/// Face ids belong to the firmware (character.h), not screen dimensions.+/// Add future faces here only when production firmware can actually select them.+const deviceFaces = [+ SelectOption(value: 2, label: 'Focus', detail: 'Your agents, at a glance.'),+];++class DeviceSettingsPanel extends StatefulWidget {+ const DeviceSettingsPanel({+ super.key,+ required this.device,+ required this.controller,+ });+ final HarnessDevice device;+ final DevicesController controller;+ @override+ State<DeviceSettingsPanel> createState() => _DeviceSettingsPanelState();+}++class _DeviceSettingsPanelState extends State<DeviceSettingsPanel> {+ double? _brightness;++ @override+ void didUpdateWidget(DeviceSettingsPanel oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.device.key != widget.device.key || !widget.device.canEdit) {+ _brightness = null;+ }+ }++ @override+ Widget build(BuildContext context) {+ final device = widget.device;+ final settings = device.status.settings;+ final controller = widget.controller;+ if (settings == null) {+ return Padding(+ padding: const EdgeInsets.all(24),+ child: Text(+ device.status.attached+ ? 'Waiting for your device’s settings. If they don’t appear, check that its firmware is up to date.'+ : 'Connect this device to see its settings.',+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ );+ }+ final enabled = device.canEdit && !controller.saving(device.key);+ void change(Map<String, Object?> patch) {+ controller.update(device.key, patch);+ }++ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (!device.hostOnline ||+ !device.hostAvailable ||+ !device.status.attached ||+ device.status.updating != null ||+ device.status.id == null) ...[+ Text(+ !device.hostOnline+ ? '${device.machineName} is offline. Showing last reported settings.'+ : !device.hostAvailable+ ? 'Reconnect or update Harness on ${device.machineName} to change settings.'+ : device.status.updating != null+ ? 'Updating to ${device.status.updating}. Keep your device connected.'+ : device.status.attached+ ? 'Update the Harness app and reconnect to change settings.'+ : 'Showing saved settings. Connect this device to ${device.machineName} to make changes.',+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ const SizedBox(height: 16),+ ],+ SettingRow(+ title: 'Brightness',+ detail: '${(_brightness ?? settings.brightness).round()}%',+ controlSemanticLabel: 'Device brightness',+ control: SizedBox(+ width: SettingRow.controlWidth,+ child: Slider(+ key: ValueKey('devices-brightness-${device.key}'),+ value: _brightness ?? settings.brightness.toDouble(),+ min: 0,+ max: 100,+ divisions: 20,+ semanticFormatterCallback: (value) => '${value.round()} percent',+ onChanged: enabled+ ? (value) => setState(() => _brightness = value)+ : null,+ onChangeEnd: enabled+ ? (value) {+ setState(() => _brightness = null);+ change({'brightness': value.round()});+ }+ : null,+ ),+ ),+ ),+ const SizedBox(height: 10),+ SettingRow(+ title: 'Sound',+ detail: 'A quiet chime when your attention is needed.',+ controlSemanticLabel: 'Device sound',+ control: Switch(+ key: ValueKey('devices-sound-${device.key}'),+ value: !settings.muted,+ onChanged: enabled ? (value) => change({'muted': !value}) : null,+ ),+ ),+ const SizedBox(height: 10),+ SettingRow(+ title: 'Reverse scrolling',+ detail: 'Change the direction of a vertical swipe.',+ controlSemanticLabel: 'Reverse scrolling',+ control: Switch(+ key: ValueKey('devices-scroll-${device.key}'),+ value: settings.scrollReversed,+ onChanged: enabled+ ? (value) => change({'scrollReversed': value})+ : null,+ ),+ ),+ const SizedBox(height: 10),+ SettingRow(+ title: 'Voice language',+ detail: 'The language you speak to this device.',+ control: SizedBox(+ width: SettingRow.controlWidth,+ child: enabled+ ? AppSelectField<String>(+ semanticLabel: 'Device voice language',+ value: settings.voiceLang,+ options: [+ const SelectOption(value: 'en', label: 'English'),+ const SelectOption(value: 'vi', label: 'Tiếng Việt'),+ const SelectOption(value: 'es', label: 'Español'),+ const SelectOption(value: 'fr', label: 'Français'),+ const SelectOption(value: 'ja', label: '日本語'),+ const SelectOption(value: 'it', label: 'Italiano'),+ if (!const [+ 'en',+ 'vi',+ 'es',+ 'fr',+ 'ja',+ 'it',+ ].contains(settings.voiceLang))+ SelectOption(+ value: settings.voiceLang,+ label: settings.voiceLang,+ ),+ ],+ onChanged: (value) => change({'voiceLang': value}),+ )+ : Text(+ _languageLabel(settings.voiceLang),+ style: DesktopChrome.control(),+ ),+ ),+ ),+ const SizedBox(height: 12),+ Semantics(+ liveRegion: true,+ child: Text(+ controller.saving(device.key)+ ? 'Saving to ${device.name}…'+ : controller.deviceError(device.key) ??+ 'Settings are saved on this device.',+ style: DesktopChrome.metadata(+ color: controller.deviceError(device.key) == null+ ? DesktopChrome.muted+ : Theme.of(context).colorScheme.error,+ ),+ ),+ ),+ ],+ );+ }+}++String _languageLabel(String code) =>+ const {+ 'en': 'English',+ 'vi': 'Tiếng Việt',+ 'es': 'Español',+ 'fr': 'Français',+ 'ja': '日本語',+ 'it': 'Italiano',+ }[code] ??+ code;++Future<void> showDeviceFaces(BuildContext context) => showAppDialog<void>(+ context: context,+ builder: (context) => Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 440),+ child: DesktopDialogSurface(+ child: SingleChildScrollView(+ child: Padding(+ padding: const EdgeInsets.all(28),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ DesktopDialogHeader(+ title: 'Faces',+ padding: EdgeInsets.zero,+ onClose: () => Navigator.of(context).pop(),+ ),+ const SizedBox(height: 28),+ for (final face in deviceFaces) ...[+ const Center(child: FocusFacePreview()),+ const SizedBox(height: 22),+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Text(face.label, style: DesktopChrome.heading()),+ const SizedBox(width: 8),+ Icon(+ AppIcons.circleCheck,+ color: DesktopChrome.accent,+ size: 20,+ ),+ ],+ ),+ const SizedBox(height: 8),+ Text(+ face.detail!,+ textAlign: TextAlign.center,+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ ],+ const SizedBox(height: 20),+ Text(+ 'Focus is the included face. New faces will appear here as they become available.',+ textAlign: TextAlign.center,+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 24),+ FilledButton(+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Done'),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ ),+);++/// A quiet, schematic preview, not fabricated live agent telemetry.+class FocusFacePreview extends StatelessWidget {+ const FocusFacePreview({super.key, this.size = 156});+ final double size;+ @override+ Widget build(BuildContext context) => Container(+ width: size,+ height: size,+ decoration: BoxDecoration(+ color: const Color(0xff141414),+ shape: BoxShape.circle,+ border: Border.all(color: const Color(0xff393939), width: 3),+ ),+ child: Center(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ AppIcons.circle,+ size: size * .16,+ color: const Color(0xffbababa),+ ),+ SizedBox(height: size * .065),+ Text(+ 'Focus',+ style: DesktopChrome.text(+ color: Colors.white,+ size: size * .14,+ medium: true,+ ),+ ),+ ],+ ),+ ),+ );+}diff --git a/desktop/lib/devices/device_setup_dialog.dart b/desktop/lib/devices/device_setup_dialog.dartnew file mode 100644index 000000000..15aeec364--- /dev/null+++ b/desktop/lib/devices/device_setup_dialog.dart@@ -0,0 +1,218 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/app_select_field.dart';+import '../widgets/desktop_chrome.dart';+import 'device_artwork.dart';+import 'devices_controller.dart';++Future<String?> showDeviceSetup(+ BuildContext context,+ DevicesController controller, {+ HarnessDevice? editing,+}) => showAppDialog<String>(+ context: context,+ builder: (_) => _DeviceSetup(controller: controller, editing: editing),+);++class _DeviceSetup extends StatefulWidget {+ const _DeviceSetup({required this.controller, this.editing});+ final DevicesController controller;+ final HarnessDevice? editing;+ @override+ State<_DeviceSetup> createState() => _DeviceSetupState();+}++class _DeviceSetupState extends State<_DeviceSetup> {+ late final _name = TextEditingController(text: widget.editing?.name ?? '');+ late final Set<String> _initial;+ late var _model = widget.editing?.model ?? HarnessDeviceModel.harness;+ String? _selected, _validation;++ @override+ void initState() {+ super.initState();+ _initial = widget.controller.devices.map((d) => d.key).toSet();+ }++ @override+ void dispose() {+ _name.dispose();+ super.dispose();+ }++ void _finish(HarnessDevice device) {+ final name = _name.text.trim().isEmpty ? device.name : _name.text.trim();+ if (name.length > 60) {+ setState(() => _validation = 'Use 60 characters or fewer.');+ return;+ }+ widget.controller.rename(device.key, name, _model);+ Navigator.of(context).pop(device.key);+ }++ @override+ Widget build(BuildContext context) => Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 500),+ child: DesktopDialogSurface(+ child: SingleChildScrollView(+ child: Padding(+ padding: const EdgeInsets.all(28),+ child: ListenableBuilder(+ listenable: widget.controller,+ builder: (context, _) {+ final connected = widget.controller.devices+ .where((d) => d.hostOnline && d.status.attached)+ .toList();+ final selected =+ widget.editing ??+ connected.where((d) => d.key == _selected).firstOrNull ??+ connected+ .where((d) => !_initial.contains(d.key))+ .firstOrNull;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ DesktopDialogHeader(+ title: widget.editing == null+ ? 'Add a device'+ : 'Device details',+ padding: EdgeInsets.zero,+ onClose: () => Navigator.of(context).pop(),+ ),+ if (widget.editing == null) ...[+ const SizedBox(height: 20),+ ClipRRect(+ borderRadius: BorderRadius.circular(16),+ child: const SizedBox(+ height: 172,+ child: DeviceArtwork(side: true),+ ),+ ),+ const SizedBox(height: 20),+ Text(+ 'Plug in. Make it yours.',+ style: DesktopChrome.heading(),+ ),+ const SizedBox(height: 8),+ Text(+ 'Connect your device by USB-C to any computer in your account. Keep Harness running on that computer; the device will appear here automatically.',+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ const SizedBox(height: 20),+ ] else+ const SizedBox(height: 20),+ Text('Model', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 6),+ AppSelectField<HarnessDeviceModel>(+ semanticLabel: 'Device model',+ value: _model,+ options: [+ for (final model in HarnessDeviceModel.values)+ SelectOption(value: model, label: model.label),+ ],+ onChanged: (value) => setState(() => _model = value),+ ),+ if (widget.editing == null) ...[+ const SizedBox(height: 18),+ if (connected.isEmpty)+ Semantics(+ liveRegion: true,+ child: Text(+ 'Waiting for a USB connection…',+ style: DesktopChrome.text(+ color: DesktopChrome.muted,+ ),+ ),+ )+ else ...[+ Text(+ 'Connected devices',+ style: DesktopChrome.control(medium: true),+ ),+ const SizedBox(height: 6),+ for (final device in connected)+ ListTile(+ contentPadding: EdgeInsets.zero,+ title: Text(device.name),+ subtitle: Text(+ '${device.machineName} · ${device.status.mac ?? device.status.id ?? 'USB device'}',+ ),+ trailing: Icon(+ selected?.key == device.key+ ? AppIcons.circleCheck+ : AppIcons.circle,+ size: 20,+ color: selected?.key == device.key+ ? DesktopChrome.accent+ : DesktopChrome.muted,+ ),+ onTap: () =>+ setState(() => _selected = device.key),+ selected: selected?.key == device.key,+ ),+ ],+ ],+ if (selected != null) ...[+ const SizedBox(height: 18),+ TextField(+ controller: _name,+ autofocus: widget.editing != null,+ maxLength: 60,+ textInputAction: TextInputAction.done,+ decoration: InputDecoration(+ labelText: 'Device name',+ hintText: selected.name,+ errorText: _validation,+ counterText: '',+ ),+ onSubmitted: (_) => _finish(selected),+ ),+ const SizedBox(height: 8),+ Text(+ 'Name and model are saved on this computer.',+ style: DesktopChrome.metadata(),+ ),+ ] else ...[+ const SizedBox(height: 12),+ Text(+ 'Not appearing? Try a data cable instead of a charging-only cable, or connect directly to a USB port.',+ style: DesktopChrome.metadata(),+ ),+ ],+ const SizedBox(height: 24),+ Wrap(+ alignment: WrapAlignment.end,+ spacing: 10,+ runSpacing: 8,+ children: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: selected == null+ ? null+ : () => _finish(selected),+ child: Text(+ widget.editing == null ? 'Finish setup' : 'Save',+ ),+ ),+ ],+ ),+ ],+ );+ },+ ),+ ),+ ),+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/devices/devices_controller.dart b/desktop/lib/devices/devices_controller.dartnew file mode 100644index 000000000..a8b5fc848--- /dev/null+++ b/desktop/lib/devices/devices_controller.dart@@ -0,0 +1,431 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';+import '../state/dial_status.dart';+import 'device_hosts.dart';++enum HarnessDeviceModel {+ harness('Harness'),+ pro('Harness Pro');++ const HarnessDeviceModel(this.label);+ final String label;+}++/// A saved identity and the latest state of that particular piece of hardware.+/// Retail models are labels chosen during setup: production USB firmware does+/// not report a retail SKU, so a touch-controller name must not imply Pro.+class HarnessDevice {+ const HarnessDevice({+ required this.key,+ required this.name,+ required this.model,+ required this.status,+ this.machineId = 'local',+ this.machineName = 'This computer',+ this.hostOnline = true,+ this.hostAvailable = true,+ this.local = true,+ });++ final String key, name;+ final HarnessDeviceModel model;+ final DialStatus status;+ final String machineId, machineName;+ final bool hostOnline, hostAvailable, local;+ bool get canEdit =>+ hostOnline &&+ hostAvailable &&+ status.attached &&+ status.id != null &&+ status.settings != null &&+ status.updating == null;+ String get connectionLabel => !hostOnline+ ? 'Computer offline'+ : !hostAvailable+ ? 'Unavailable'+ : status.updating != null+ ? 'Updating'+ : status.attached+ ? 'Connected'+ : 'Disconnected';++ HarnessDevice copyWith({+ String? name,+ HarnessDeviceModel? model,+ DialStatus? status,+ String? machineId,+ String? machineName,+ bool? hostOnline,+ bool? hostAvailable,+ bool? local,+ }) => HarnessDevice(+ key: key,+ name: name ?? this.name,+ model: model ?? this.model,+ status: status ?? this.status,+ machineId: machineId ?? this.machineId,+ machineName: machineName ?? this.machineName,+ hostOnline: hostOnline ?? this.hostOnline,+ hostAvailable: hostAvailable ?? this.hostAvailable,+ local: local ?? this.local,+ );++ Map<String, Object?> toJson() => {+ 'key': key,+ 'name': name,+ 'model': model.name,+ 'machineId': machineId,+ 'machineName': machineName,+ 'status': {+ 'attached': false,+ 'id': status.id,+ 'mac': status.mac,+ 'fw': status.fw,+ 'hw': status.hw,+ if (status.settings != null) 'settings': status.settings!.toJson(),+ },+ };++ static HarnessDevice? fromJson(Object? raw) {+ if (raw is! Map ||+ raw['key'] is! String ||+ raw['name'] is! String ||+ raw['status'] is! Map) {+ return null;+ }+ final key = raw['key'] as String;+ final name = raw['name'] as String;+ if (key.isEmpty || name.trim().isEmpty) return null;+ return HarnessDevice(+ key: key,+ name: name,+ machineId: raw['machineId'] is String+ ? raw['machineId'] as String+ : 'local',+ machineName: raw['machineName'] is String+ ? raw['machineName'] as String+ : 'This computer',+ hostOnline: false,+ local: raw['machineId'] == null || raw['machineId'] == 'local',+ model: raw['model'] == 'pro'+ ? HarnessDeviceModel.pro+ : HarnessDeviceModel.harness,+ status: DialStatus.fromJson({+ ...Map<String, dynamic>.from(raw['status'] as Map),+ 'attached': false,+ 'updating': null,+ }),+ );+ }+}++/// Local, account-scoped device names and last readings. USB discovery owns+/// connection state; reopening a saved library cannot manufacture a device.+class DevicesController extends ChangeNotifier {+ DevicesController({+ this.dial,+ this.hosts,+ required String accountId,+ this.sendSettings,+ this.sendHostSettings,+ this.storage,+ this.confirmationTimeout = const Duration(seconds: 8),+ }) : storageKey = 'harness_devices_v1.${Uri.encodeComponent(accountId)}' {+ assert(dial != null || hosts != null);+ assert(sendSettings != null || sendHostSettings != null);+ dial?.addListener(_sync);+ hosts?.addListener(_sync);+ }++ final DialState? dial;+ final DeviceHosts? hosts;+ final LocalKeyValueStore? storage;+ final String storageKey;+ final Future<bool> Function(String id, Map<String, Object?> patch)?+ sendSettings;+ final Future<bool> Function(+ String machineId,+ String id,+ Map<String, Object?> patch,+ )?+ sendHostSettings;+ final Duration confirmationTimeout;+ final _devices = <String, HarnessDevice>{};+ final _pending = <String, Map<String, Object?>>{};+ final _timers = <String, Timer>{};+ final _errors = <String, String>{};+ Future<void> _writes = Future.value();+ Future<void>? _loading;+ bool loaded = false, _disposed = false, _readFailed = false;+ String? error;++ List<HarnessDevice> get devices => List.unmodifiable(_devices.values);+ List<DeviceHost> get computers => hosts?.hosts ?? const [];+ HarnessDevice? device(String key) => _devices[key];+ bool saving(String key) => _pending.containsKey(key);+ String? deviceError(String key) => _errors[key];+ Future<void> get settled => _writes;++ Future<void> load() => _loading ??= _load();+ Future<void> _load() async {+ try {+ final raw = await storage?.read(storageKey);+ if (_disposed) return;+ if (raw != null) {+ final rows = jsonDecode(raw);+ if (rows is! List) {+ throw const FormatException('Invalid device library');+ }+ for (final row in rows) {+ final device = HarnessDevice.fromJson(row);+ if (device != null) _devices.putIfAbsent(device.key, () => device);+ }+ }+ _readFailed = false;+ error = null;+ } catch (_) {+ if (_disposed) return;+ _readFailed = true;+ error =+ 'Couldn’t load saved devices. Connected devices are still available.';+ }+ if (_disposed) return;+ loaded = true;+ _sync();+ }++ static String identity(DialStatus status) => status.mac != null+ ? 'mac:${status.mac!.toLowerCase()}'+ : status.id != null+ ? 'usb:${status.id}'+ : 'legacy';++ void _sync() {+ if (_disposed || !loaded) return;+ final before = jsonEncode(_devices.values.map((d) => d.toJson()).toList());+ final seen = <String>{};+ final sources =+ hosts?.hosts ??+ [+ DeviceHost(+ id: 'local',+ name: 'This computer',+ online: true,+ local: true,+ available: true,+ status: DialStatus(+ attached: dial!.status.attached,+ devices: dial!.devices,+ ),+ ),+ ];+ for (final host in sources) {+ for (final live in host.devices) {+ final identityKey = identity(live);+ // The greeting can add a MAC after the USB identity was first reported.+ // Keep the saved key (and selection) when that happens, or ports change.+ final known = _devices.values+ .where(+ (d) =>+ (d.machineId == host.id ||+ (d.machineId == 'local' && host.local)) &&+ (d.key == identityKey ||+ (live.mac != null &&+ d.status.mac?.toLowerCase() ==+ live.mac!.toLowerCase()) ||+ (live.id != null &&+ d.status.id == live.id &&+ (live.mac == null || d.status.mac == null))),+ )+ .firstOrNull;+ final key =+ known?.key ??+ (host.id == 'local'+ ? identityKey+ : '${Uri.encodeComponent(host.id)}/$identityKey');+ seen.add(key);+ final number = _devices.length + 1;+ final observed = DialStatus(+ attached: host.online && live.attached,+ id: live.id,+ mac: live.mac ?? known?.status.mac,+ fw: live.fw ?? known?.status.fw,+ hw: live.hw ?? known?.status.hw,+ updating: live.updating,+ // A disconnect frame may omit readings. Preserve them for reference,+ // but require fresh settings when a connected device greets us again.+ settings:+ live.settings ?? (live.attached ? null : known?.status.settings),+ );+ _devices[key] =+ known?.copyWith(+ status: observed,+ machineId: host.id,+ machineName: host.name,+ hostOnline: host.online,+ hostAvailable: host.available,+ local: host.local,+ ) ??+ HarnessDevice(+ key: key,+ name: number == 1 ? 'My Harness' : 'Harness $number',+ model: HarnessDeviceModel.harness,+ status: observed,+ machineId: host.id,+ machineName: host.name,+ hostOnline: host.online,+ hostAvailable: host.available,+ local: host.local,+ );+ final pending = _pending[key];+ final held = live.settings?.toJson();+ if (pending != null &&+ (!host.online ||+ !host.available ||+ !live.attached ||+ live.updating != null)) {+ _finish(+ key,+ live.updating != null+ ? 'The device started updating before confirming the change. Try again after the update.'+ : 'Device disconnected. Reconnect to change its settings.',+ );+ } else if (pending != null &&+ held != null &&+ pending.entries.every((e) => held[e.key] == e.value)) {+ _finish(key);+ }+ }+ }+ for (final key in _devices.keys.toList()) {+ if (seen.contains(key)) continue;+ final device = _devices[key]!;+ final status = device.status;+ _devices[key] = device.copyWith(+ hostOnline: sources.any((h) => h.id == device.machineId && h.online),+ status: DialStatus(+ attached: false,+ id: status.id,+ mac: status.mac,+ fw: status.fw,+ hw: status.hw,+ settings: status.settings,+ ),+ );+ if (_pending.containsKey(key)) {+ _finish(key, 'Device disconnected. Reconnect to change its settings.');+ }+ }+ final after = jsonEncode(_devices.values.map((d) => d.toJson()).toList());+ if (before != after) _save(after);+ notifyListeners();+ }++ void rename(String key, String name, HarnessDeviceModel model) {+ final device = _devices[key];+ final clean = name.trim();+ if (device == null || clean.isEmpty || clean.length > 60 || _disposed) {+ return;+ }+ _devices[key] = device.copyWith(name: clean, model: model);+ _save(jsonEncode(_devices.values.map((d) => d.toJson()).toList()));+ notifyListeners();+ }++ void _save(String encoded) {+ final store = storage;+ if (store == null || _readFailed) return;+ _writes = _writes+ .then((_) => store.write(storageKey, encoded))+ .then((_) {+ if (!_disposed && error != null) {+ error = null;+ notifyListeners();+ }+ })+ .catchError((Object _) {+ if (_disposed) return;+ error = 'Couldn’t save your device library. Try again.';+ notifyListeners();+ });+ }++ Future<void> retrySave() async {+ if (_readFailed) {+ _loading = null;+ await load();+ }+ if (!_disposed) {+ _save(jsonEncode(_devices.values.map((d) => d.toJson()).toList()));+ }+ }++ Future<void> update(String key, Map<String, Object?> patch) async {+ final device = _devices[key];+ if (_disposed ||+ device == null ||+ !device.canEdit ||+ saving(key) ||+ patch.isEmpty) {+ return;+ }+ final held = device.status.settings!.toJson();+ if (patch.entries.every((e) => held[e.key] == e.value)) return;+ final request = Map<String, Object?>.of(patch);+ _pending[key] = request;+ _errors.remove(key);+ _timers[key] = Timer(confirmationTimeout, () {+ _finish(+ key,+ 'The change wasn’t confirmed. Check the connection and try again.',+ );+ if (!_disposed) notifyListeners();+ });+ notifyListeners();+ try {+ final sent =+ await (sendHostSettings?.call(+ device.machineId,+ device.status.id!,+ patch,+ ) ??+ sendSettings!(device.status.id!, patch));+ if (_disposed || !identical(_pending[key], request)) return;+ if (!sent) {+ _finish(+ key,+ 'Couldn’t reach this device. Check the connection and try again.',+ );+ notifyListeners();+ }+ } catch (_) {+ if (_disposed || !identical(_pending[key], request)) return;+ _finish(+ key,+ 'Couldn’t reach this device. Check the connection and try again.',+ );+ notifyListeners();+ }+ }++ void _finish(String key, [String? message]) {+ _pending.remove(key);+ _timers.remove(key)?.cancel();+ if (message != null) _errors[key] = message;+ }++ @override+ void dispose() {+ _disposed = true;+ dial?.removeListener(_sync);+ hosts?.removeListener(_sync);+ for (final timer in _timers.values) {+ timer.cancel();+ }+ super.dispose();+ }+}diff --git a/desktop/lib/devices/devices_harness_controller.dart b/desktop/lib/devices/devices_harness_controller.dartnew file mode 100644index 000000000..8abea4d08--- /dev/null+++ b/desktop/lib/devices/devices_harness_controller.dart@@ -0,0 +1,137 @@+import 'package:flutter/foundation.dart';++import '../core/models.dart';+import '../core/project_folder.dart';+import '../state/app_state.dart';++const devicesHarnessId = 'autonomous/devices';++/// One Devices conversation, opened through the normal DSH creation/receipt path.+class DevicesHarnessController extends ChangeNotifier {+ DevicesHarnessController(this.app);+ final AppNotifier app;+ Future<void>? _opening;+ MachineState? _owner;+ String? _account;+ AgentCreationAttempt? _creation;+ ProjectFolderRequest? _folder;+ bool _disposed = false;+ String? error;+ bool get opening => _opening != null;++ Future<void> open() {+ if (_opening != null) return _opening!;+ error = null;+ _opening = _open().whenComplete(() {+ _opening = null;+ if (!_disposed) notifyListeners();+ });+ notifyListeners();+ return _opening!;+ }++ bool _current(MachineState owner) =>+ !_disposed &&+ app.devicesEnabled &&+ app.currentUser?.id == _account &&+ identical(app.stateOf(owner.machine.machineId), owner) &&+ app.swarms.any((tab) => tab.isDevices);++ Future<void> _open() async {+ if (!app.devicesEnabled) return;+ final owner = app.machineStates.values+ .where((machine) => machine.isLocalMachine && !machine.machine.isShared)+ .firstOrNull;+ if (owner == null || owner.isOffline) {+ error =+ 'Connect Harness on this computer to open the Devices conversation.';+ return;+ }+ if (!identical(_owner, owner) || _account != app.currentUser?.id) {+ _owner = owner;+ _account = app.currentUser?.id;+ _creation = null;+ _folder = null;+ }+ final machineId = owner.machine.machineId;+ Agent? existing() => owner.agents+ .where((agent) => agent.dsh == devicesHarnessId)+ .firstOrNull;+ try {+ if (owner.agentsLoadInFlight case final loading?) {+ await loading;+ } else if (owner.agentLoadStatus != AgentLoadStatus.loaded) {+ await app.reloadMachineData(machineId);+ }+ if (!_current(owner)) return;+ if (owner.agentLoadStatus != AgentLoadStatus.loaded ||+ owner.agentsLoadError != null) {+ error = 'Couldn’t read existing conversations. Reconnect Harness and try again.';+ return;+ }+ var agent = existing();+ if (agent == null) {+ await app.probeEngines(machineId);+ if (!_current(owner)) return;+ final engine = [+ 'codex',+ 'claude',+ 'opencode',+ ].where((id) => owner.engines[id]?.installed == true).firstOrNull;+ if (engine == null) {+ error = 'Install Codex, Claude Code, or OpenCode to open the Devices conversation.';+ return;+ }+ if (_creation != null &&+ !_creation!.awaitingConfirmation &&+ _creation!.agentId == null) {+ _creation = null;+ }+ _creation ??= AgentCreationAttempt(background: true);+ _folder ??= ProjectFolderRequest.generated(+ label: 'devices',+ at: DateTime.now(),+ );+ final failure = await app.createAgent(+ machineId,+ engine: engine,+ folder: null,+ projectFolder: _folder,+ dsh: devicesHarnessId,+ name: 'Devices',+ bypassPermission: false,+ permissionMode: 'ask',+ attempt: _creation,+ );+ if (!_current(owner)) return;+ if (failure != null) {+ error = failure;+ return;+ }+ agent = existing();+ }+ if (agent == null) {+ error = 'Devices is still starting. Try again in a moment.';+ return;+ }+ if (agent.isStopped) {+ final resumed = await app.resumeAgent(machineId, agent.id);+ if (!_current(owner)) return;+ if (resumed.error != null) {+ error = resumed.error;+ return;+ }+ }+ if (!_current(owner)) return;+ await app.showDevicesTerminal(machineId, agent.id);+ } catch (_) {+ if (_current(owner)) error = 'Couldn’t open Devices. Update Harness on this computer and try again.';+ }+ }++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }+}diff --git a/desktop/lib/devices/devices_screen.dart b/desktop/lib/devices/devices_screen.dartnew file mode 100644index 000000000..6bfe5863e--- /dev/null+++ b/desktop/lib/devices/devices_screen.dart@@ -0,0 +1,630 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:url_launcher/url_launcher.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/skeleton.dart';+import '../shared/widgets/app_icon_button.dart';+import '../core/test_run.dart';+import '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import 'device_artwork.dart';+import 'device_settings.dart';+import 'device_setup_dialog.dart';+import 'devices_controller.dart';++final harnessDeviceShopUrl = Uri.parse(+ 'https://www.autonomous.ai/harness-device',+);++class DevicesTab extends StatefulWidget {+ const DevicesTab({+ super.key,+ required this.notifier,+ this.conversationOpening = false,+ this.conversationError,+ this.onOpenConversation,+ });+ final AppNotifier notifier;+ final bool conversationOpening;+ final String? conversationError;+ final VoidCallback? onOpenConversation;+ @override+ State<DevicesTab> createState() => _DevicesTabState();+}++class _DevicesTabState extends State<DevicesTab> {+ late final controller = DevicesController(+ hosts: widget.notifier.deviceHosts,+ accountId: widget.notifier.currentUser?.id ?? 'guest',+ storage: widget.notifier.deviceLibraryStorage,+ sendHostSettings: widget.notifier.setHostDeviceSettings,+ );+ Timer? _refresh;+ @override+ void initState() {+ super.initState();+ unawaited(widget.notifier.refreshDevices());+ if (!kUnderTest) {+ _refresh = Timer.periodic(+ const Duration(seconds: 10),+ (_) => unawaited(widget.notifier.refreshDevices()),+ );+ }+ }++ @override+ void dispose() {+ _refresh?.cancel();+ controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => DevicesScreen(+ controller: controller,+ onRefresh: widget.notifier.refreshDevices,+ conversationOpening: widget.conversationOpening,+ conversationError: widget.conversationError,+ onOpenConversation: widget.onOpenConversation,+ );+}++class DevicesScreen extends StatefulWidget {+ const DevicesScreen({+ super.key,+ required this.controller,+ this.openShop,+ this.onRefresh,+ this.conversationOpening = false,+ this.conversationError,+ this.onOpenConversation,+ });+ final DevicesController controller;+ final Future<bool> Function(Uri)? openShop;+ final Future<void> Function()? onRefresh;+ final bool conversationOpening;+ final String? conversationError;+ final VoidCallback? onOpenConversation;+ @override+ State<DevicesScreen> createState() => _DevicesScreenState();+}++class _DevicesScreenState extends State<DevicesScreen> {+ String? _selectedKey;+ String? _shopError;+ final _cards = ScrollController();++ @override+ void initState() {+ super.initState();+ unawaited(widget.controller.load());+ }++ @override+ void dispose() {+ _cards.dispose();+ super.dispose();+ }++ Future<void> _shop() async {+ var opened = false;+ try {+ opened =+ await (widget.openShop?.call(harnessDeviceShopUrl) ??+ launchUrl(+ harnessDeviceShopUrl,+ mode: LaunchMode.externalApplication,+ ));+ } catch (_) {+ /* The inline retry remains beside the action. */+ }+ if (mounted) {+ setState(+ () => _shopError = opened ? null : 'Couldn’t open the shop. Try again.',+ );+ }+ }++ Future<void> _setup({HarnessDevice? editing}) async {+ final key = await showDeviceSetup(+ context,+ widget.controller,+ editing: editing,+ );+ if (mounted && key != null) setState(() => _selectedKey = key);+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return ColoredBox(+ color: grid.AppPalette.windowBg,+ child: ListenableBuilder(+ listenable: widget.controller,+ builder: (context, _) => LayoutBuilder(+ builder: (context, bounds) {+ final devices = widget.controller.devices;+ final selected =+ devices.where((d) => d.key == _selectedKey).firstOrNull ??+ devices.where((d) => d.status.attached).firstOrNull ??+ devices.firstOrNull;+ _selectedKey ??= selected?.key;+ final pad = bounds.maxWidth < 640 ? 20.0 : 40.0;+ return SingleChildScrollView(+ key: const PageStorageKey('devices-page'),+ padding: EdgeInsets.fromLTRB(pad, 36, pad, 40),+ child: Center(+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 1120),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Wrap(+ alignment: WrapAlignment.spaceBetween,+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 24,+ runSpacing: 18,+ children: [+ Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('Devices', style: grid.AppType.display()),+ const SizedBox(height: 7),+ Text(+ 'All your devices. Across your computers.',+ style: DesktopChrome.text(+ color: DesktopChrome.muted,+ ),+ ),+ ],+ ),+ Wrap(+ spacing: 10,+ runSpacing: 10,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ if (widget.onRefresh != null)+ AppIconButton(+ tooltip: 'Refresh devices',+ onPressed: widget.onRefresh,+ icon: AppIcons.refreshCw,+ ),+ TextButton(+ onPressed: _shop,+ child: const Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text('Shop'),+ SizedBox(width: 7),+ Icon(AppIcons.arrowUpRight, size: 16),+ ],+ ),+ ),+ FilledButton.icon(+ key: const Key('devices-add'),+ onPressed: () => _setup(),+ icon: const Icon(AppIcons.plus, size: 16),+ label: const Text('Add device'),+ ),+ ],+ ),+ ],+ ),+ if (_shopError != null) ...[+ const SizedBox(height: 12),+ Semantics(+ liveRegion: true,+ child: Text(+ _shopError!,+ style: DesktopChrome.metadata(+ color: Theme.of(context).colorScheme.error,+ ),+ ),+ ),+ ],+ if (widget.conversationOpening ||+ widget.conversationError != null) ...[+ const SizedBox(height: 16),+ Wrap(+ spacing: 12,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ Text(+ widget.conversationError ??+ 'Opening the Devices conversation…',+ style: DesktopChrome.metadata(),+ ),+ if (!widget.conversationOpening)+ TextButton(+ onPressed: widget.onOpenConversation,+ child: const Text('Retry'),+ ),+ ],+ ),+ ],+ if (widget.controller.error case final error?) ...[+ const SizedBox(height: 16),+ Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 12,+ children: [+ Text(error, style: DesktopChrome.metadata()),+ TextButton(+ onPressed: widget.controller.retrySave,+ child: const Text('Retry'),+ ),+ ],+ ),+ ],+ const SizedBox(height: 32),+ for (final host in widget.controller.computers)+ if (host.error != null) ...[+ Text(+ '${host.name}: ${host.error}',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 12),+ ],+ if (!widget.controller.loaded)+ const SkeletonBlock(+ child: Skeleton(+ width: double.infinity,+ height: 320,+ radius: 18,+ ),+ )+ else if (selected == null)+ _EmptyDevices(onAdd: () => _setup(), onShop: _shop)+ else ...[+ Text(+ '${devices.length} ${devices.length == 1 ? 'device' : 'devices'}',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 12),+ LayoutBuilder(+ builder: (context, constraints) {+ final scale = MediaQuery.textScalerOf(context)+ .scale(1);+ final cardWidth = math.max(+ 194.0,+ math.min(220.0, (constraints.maxWidth - 64) / 5),+ );+ return Scrollbar(+ controller: _cards,+ child: SingleChildScrollView(+ controller: _cards,+ scrollDirection: Axis.horizontal,+ padding: const EdgeInsets.only(bottom: 14),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (+ var i = 0;+ i < devices.length;+ i+++ ) ...[+ if (i > 0) const SizedBox(width: 16),+ SizedBox(+ width: cardWidth * math.min(scale, 1.4),+ child: _DeviceCard(+ device: devices[i],+ selected:+ devices[i].key == selected.key,+ onPressed: () => setState(+ () => _selectedKey = devices[i].key,+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ );+ },+ ),+ const SizedBox(height: 22),+ Divider(color: DesktopChrome.rim, height: 1),+ const SizedBox(height: 26),+ Wrap(+ alignment: WrapAlignment.spaceBetween,+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 20,+ runSpacing: 8,+ children: [+ Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ selected.name,+ style: grid.AppType.title(),+ ),+ const SizedBox(height: 5),+ Text(+ '${selected.model.label} · ${selected.machineName} · ${selected.connectionLabel}',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ TextButton(+ onPressed: () => _setup(editing: selected),+ child: const Text('Edit details'),+ ),+ ],+ ),+ const SizedBox(height: 24),+ LayoutBuilder(+ builder: (context, constraints) {+ final showcase = _DeviceShowcase(device: selected);+ final settings = DeviceSettingsPanel(+ key: ValueKey(selected.key),+ device: selected,+ controller: widget.controller,+ );+ if (constraints.maxWidth < 850 ||+ MediaQuery.textScalerOf(context).scale(1) >+ 1.5) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ showcase,+ const SizedBox(height: 24),+ settings,+ ],+ );+ }+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(width: 340, child: showcase),+ const SizedBox(width: 36),+ Expanded(child: settings),+ ],+ );+ },+ ),+ ],+ ],+ ),+ ),+ ),+ );+ },+ ),+ ),+ );+ }+}++class _DeviceCard extends StatelessWidget {+ const _DeviceCard({+ required this.device,+ required this.selected,+ required this.onPressed,+ });+ final HarnessDevice device;+ final bool selected;+ final VoidCallback onPressed;++ @override+ Widget build(BuildContext context) => Semantics(+ selected: selected,+ button: true,+ label:+ '${device.name}, ${device.model.label}, ${device.machineName}, ${device.connectionLabel}',+ child: Material(+ color: selected ? DesktopChrome.selection : DesktopChrome.surface,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(18),+ side: BorderSide(+ color: selected ? DesktopChrome.accent : DesktopChrome.rim,+ width: selected ? 1.5 : 1,+ ),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ key: ValueKey('device-card-${device.key}'),+ onTap: onPressed,+ child: ExcludeSemantics(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const SizedBox(height: 116, child: DeviceArtwork(closeUp: true)),+ Padding(+ padding: const EdgeInsets.fromLTRB(15, 13, 15, 14),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Expanded(+ child: Tooltip(+ message: device.name,+ child: Text(+ device.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.text(medium: true),+ ),+ ),+ ),+ if (selected) ...[+ const SizedBox(width: 5),+ Icon(+ AppIcons.circleCheck,+ size: 16,+ color: DesktopChrome.accent,+ ),+ ],+ ],+ ),+ const SizedBox(height: 3),+ Text(device.model.label, style: DesktopChrome.metadata()),+ const SizedBox(height: 3),+ Text(+ device.machineName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 9),+ Text(+ device.connectionLabel,+ style: DesktopChrome.metadata(+ color: device.status.attached+ ? DesktopChrome.foreground+ : DesktopChrome.muted,+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+}++class _DeviceShowcase extends StatelessWidget {+ const _DeviceShowcase({required this.device});+ final HarnessDevice device;+ @override+ Widget build(BuildContext context) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(18),+ child: const SizedBox(+ height: 205,+ child: DeviceArtwork(side: true, closeUp: true),+ ),+ ),+ const SizedBox(height: 16),+ Material(+ color: DesktopChrome.surface,+ borderRadius: BorderRadius.circular(14),+ child: InkWell(+ key: const Key('devices-faces'),+ borderRadius: BorderRadius.circular(14),+ onTap: () => showDeviceFaces(context),+ child: Padding(+ padding: const EdgeInsets.all(14),+ child: Row(+ children: [+ const FocusFacePreview(size: 52),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('Faces', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 3),+ Text('Focus', style: DesktopChrome.metadata()),+ ],+ ),+ ),+ Icon(+ AppIcons.chevronRight,+ size: 16,+ color: DesktopChrome.muted,+ ),+ ],+ ),+ ),+ ),+ ),+ const SizedBox(height: 16),+ Text(+ [+ if (device.status.fw != null) 'Firmware ${device.status.fw}',+ if (device.status.settings != null)+ '${device.status.settings!.face} px display',+ ].join(' · '),+ style: DesktopChrome.metadata(),+ ),+ if (device.status.mac ?? device.status.id case final id?) ...[+ const SizedBox(height: 4),+ SelectableText(id, style: DesktopChrome.metadata()),+ ],+ ],+ );+}++class _EmptyDevices extends StatelessWidget {+ const _EmptyDevices({required this.onAdd, required this.onShop});+ final VoidCallback onAdd, onShop;+ @override+ Widget build(BuildContext context) => LayoutBuilder(+ builder: (context, constraints) {+ final copy = Padding(+ padding: const EdgeInsets.all(36),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'A little closer\nto your work.',+ style: grid.AppType.display(),+ ),+ const SizedBox(height: 18),+ Text(+ 'Your agents, at a glance. A quiet chime when they need you. Make a home for every Harness on your desk.',+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ const SizedBox(height: 28),+ Wrap(+ spacing: 10,+ runSpacing: 10,+ children: [+ FilledButton(+ onPressed: onAdd,+ child: const Text('Add your first device'),+ ),+ TextButton(+ onPressed: onShop,+ child: const Text('Shop Harness'),+ ),+ ],+ ),+ const SizedBox(height: 24),+ Text(+ 'Have a device? Connect it with a USB-C cable to get started.',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ );+ return Material(+ color: DesktopChrome.surface,+ borderRadius: BorderRadius.circular(24),+ clipBehavior: Clip.antiAlias,+ child:+ constraints.maxWidth < 760 ||+ MediaQuery.textScalerOf(context).scale(1) > 1.5+ ? Column(+ children: [+ const SizedBox(height: 260, child: DeviceArtwork(desk: true)),+ copy,+ ],+ )+ : Row(+ children: [+ Expanded(+ flex: 6,+ child: SizedBox(+ height: 440,+ child: const DeviceArtwork(desk: true),+ ),+ ),+ Expanded(flex: 5, child: copy),+ ],+ ),+ );+ },+ );+}diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex 7f3d7861b..45df008b7 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -13,6 +13,8 @@ const int e2eVersion = 1;/// to the CLI's own list, because a type missing here fails nowhere: the frame simply leaves in the/// clear, and for terminal_* the relay then drops it as TERMINAL_FRAME_REJECTED.const Set<String> encryptedDownTypes = {+ 'harness_devices_list',+ 'harness_device_settings','team','team_delivery','harness_share_list',diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 07669c572..6ddf8c5f0 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -92,6 +92,8 @@ import '../widgets/grid_model_picker.dart';import '../widgets/workspace_subscription_usage.dart';import '../store/store_mark.dart';import '../store/store_screen.dart';+import '../devices/devices_screen.dart';+import '../devices/devices_harness_controller.dart';import '../widgets/harness_start_page.dart';import '../state/toolbar_notices.dart';import '../widgets/machine_actions.dart';@@ -523,6 +525,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_shortcutsEnabled &&app.panes.isEmpty &&!app.activeSwarm.isStore &&+ !app.activeSwarm.isDevices &&!app.activeSwarm.isOrchestrator &&_newHarness == null &&_search == null &&@@ -778,6 +781,7 @@ class _SwarmScreenState extends State<SwarmScreen> {@overridevoid dispose() {+ _devicesHarness.dispose();_harnessMonitor.dispose();if (app.reviewSessionClose == _reviewSessionClose) {app.reviewSessionClose = null;@@ -1777,6 +1781,7 @@ class _SwarmScreenState extends State<SwarmScreen> {'activeId': app.activeSwarmId,'searchTooltip': _commandTooltip('Open Harness', 'harnesses.list'),'storeTooltip': _commandTooltip('Explore Harness Store', 'app.store'),+ 'devicesVisible': app.devicesEnabled,// The selected tab is drawn with keyboard focus: ⏎ goes into it.'tabsFocused': app.tabStripFocused && _tabStripFocus.hasPrimaryFocus,// Only once the slot is shown: until then (and whenever daemons are@@ -2295,6 +2300,8 @@ class _SwarmScreenState extends State<SwarmScreen> {await _openFocusedPullRequest(args['url'] as String?);case 'store':_openStore();+ case 'devices':+ _openDevices();case 'new':_newTab();case 'reopen':@@ -2923,6 +2930,7 @@ class _SwarmScreenState extends State<SwarmScreen> {requestedSplit == null &&app.panes.isEmpty &&!app.activeSwarm.isStore &&+ !app.activeSwarm.isDevices &&!app.activeSwarm.isOrchestrator;final welcomeOrigin = embedded? _newHarnessDrafts.keys@@ -3644,6 +3652,65 @@ class _SwarmScreenState extends State<SwarmScreen> {if (_menuHost && mounted) _syncNative();}+ late final _devicesHarness = DevicesHarnessController(app);+ String? _devicesAttemptedKey;++ Widget _devicesViewer(BuildContext context) {+ final key = '${app.currentUser?.id}:${app.activeSwarmId}';+ if (app.activeSwarm.isDevices &&+ app.devicesEnabled &&+ _devicesAttemptedKey != key) {+ _devicesAttemptedKey = key;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted &&+ app.activeSwarm.isDevices &&+ app.devicesEnabled &&+ key == '${app.currentUser?.id}:${app.activeSwarmId}') {+ unawaited(_devicesHarness.open());+ }+ });+ }+ return ListenableBuilder(+ listenable: _devicesHarness,+ builder: (context, _) => DevicesTab(+ key: ValueKey('devices-tab:${app.currentUser?.id}'),+ notifier: app,+ conversationOpening: _devicesHarness.opening,+ conversationError: _devicesHarness.error,+ onOpenConversation: _devicesHarness.open,+ ),+ );+ }++ void _openDevices() {+ if (!_routeIsCurrent ||+ _dialogOpen ||+ _spokenPaletteOpen ||+ !app.devicesEnabled) {+ return;+ }+ if (_newHarness case final box?) {+ if (box.locked) {+ box.warn('Check the pending creation before opening Devices.');+ return;+ }+ _closeNewHarness(restoreFocus: false);+ }+ _closeSearch(restoreFocus: false);+ _closeCommandBar(restoreFocus: false);+ dismissTransientMenus();+ app.openDevices();+ unawaited(_devicesHarness.open());+ }++ Widget _devicesButton(BuildContext context) => WorkspaceStoreButton(+ key: const ValueKey('swarm-devices-button'),+ width: WorkspaceStoreButton.widthOf(context, devices: true),+ devices: true,+ tooltip: 'Manage Harness devices',+ onPressed: _shortcutsEnabled ? _openDevices : null,+ );+// ── the daemon (daemons/README.md) ─────────────────────────────────────────/// A `daemon_*` or `pair` frame to this computer's harnessd, only while@@ -6585,6 +6652,10 @@ class _SwarmScreenState extends State<SwarmScreen> {_searchButton(theme),_notificationsButton(theme),const SizedBox(width: DesktopChrome.controlGap),+ if (app.devicesEnabled) ...[+ _devicesButton(context),+ const SizedBox(width: DesktopChrome.controlGap),+ ],WorkspaceStoreButton(key: const ValueKey('swarm-store-button'),width: WorkspaceStoreButton.widthOf(context),@@ -6790,6 +6861,9 @@ class _SwarmScreenState extends State<SwarmScreen> {paneId: paneId,),),+ devicesViewer: app.devicesEnabled+ ? _devicesViewer+ : null,companionViewer:_creatureEnabled &&_zoo.loaded@@ -7052,6 +7126,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_harnessMonitor.live.isNotEmpty ||app.panes.isNotEmpty ||app.activeSwarm.isStore ||+ app.activeSwarm.isDevices ||app.activeSwarm.isOrchestrator ||_footerPreviewCurrent;@@ -7379,7 +7454,13 @@ class _SwarmScreenState extends State<SwarmScreen> {// holds them.final actionsWidth = _titleBarActions? 0.0- : storeWidth + cell.width * 8 + DesktopChrome.controlGap;+ : storeWidth ++ cell.width * 8 ++ DesktopChrome.controlGap ++ (app.devicesEnabled+ ? WorkspaceStoreButton.widthOf(context, devices: true) ++ DesktopChrome.controlGap+ : 0);final leadingWidth = chrome?.leadingWidth(context) ?? 0.0;final tabBudget = math.max(0.0,@@ -7550,6 +7631,10 @@ class _SwarmScreenState extends State<SwarmScreen> {_searchButton(theme),_notificationsButton(theme),const SizedBox(width: DesktopChrome.controlGap),+ if (app.devicesEnabled) ...[+ _devicesButton(context),+ const SizedBox(width: DesktopChrome.controlGap),+ ],WorkspaceStoreButton(key: const ValueKey('swarm-store-button'),width: storeWidth,diff --git a/desktop/lib/settings/experimental_features.dart b/desktop/lib/settings/experimental_features.dartindex e07863312..b5f79dd1b 100644--- a/desktop/lib/settings/experimental_features.dart+++ b/desktop/lib/settings/experimental_features.dart@@ -15,6 +15,11 @@ enum ExperimentalFeature {'share_button','Share button','Show Share in the top-right corner of the workspace.',+ ),+ devicesTab(+ 'devices_tab',+ 'Devices tab',+ 'Manage your Harness devices. Show Devices next to Harness Store. Off by default.',);const ExperimentalFeature(this.id, this.label, this.description);@@ -22,6 +27,7 @@ enum ExperimentalFeature {bool get available => switch (this) {focusBarCreature => !kIsWeb && !kViewerMode,shareButton => true,+ devicesTab => !kIsWeb && !kViewerMode,};}@@ -136,15 +142,22 @@ class ExperimentalFeaturesStore extends ChangeNotifier {revision < 0 ||features is! Map ||ExperimentalFeature.values.any(- (feature) => features[feature.id] is! bool,+ (feature) =>+ features[feature.id] is! bool &&+ !(feature == ExperimentalFeature.devicesTab &&+ !features.containsKey(feature.id)),)) {throw const FormatException('Invalid account settings');}if (revision < _revision) return;_revision = revision;for (final feature in ExperimentalFeature.values) {- _choices[feature] = features[feature.id] as bool;- _available[feature] = available is! Map || available[feature.id] != false;+ // Older servers do not know this experiment. Keep their existing+ // settings usable, and leave the new feature off and unavailable.+ _choices[feature] = features[feature.id] == true;+ _available[feature] =+ features.containsKey(feature.id) &&+ (available is! Map || available[feature.id] != false);}loaded = true;}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 6fcb5e6db..d6df49b56 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -61,6 +61,8 @@ import '../core/serial_port_lease.dart';import '../autonomous_device/autonomous_device_cli.dart';import '../settings/config_store.dart';import '../settings/experimental_features.dart';+import '../core/local_key_value_store.dart';+import '../devices/device_hosts.dart';import '../stats/harness_stats.dart';import '../terminal/terminal_session.dart';import '../terminal/terminal_theme.dart';@@ -982,7 +984,11 @@ class AppNotifier extends ChangeNotifier {CurrentUserProfile? _currentUser;CurrentUserProfile? get currentUser => _currentUser;set currentUser(CurrentUserProfile? profile) {- if (_currentUser?.id != profile?.id) _closeOwnerMemories();+ if (_currentUser?.id != profile?.id) {+ _closeOwnerMemories();+ deviceHosts.clear();+ _deviceReads.clear();+ }_currentUser = profile;final id = profile?.id;experimentalFeatures.bind(@@ -1101,6 +1107,7 @@ class AppNotifier extends ChangeNotifier {bool _canReopenSwarm(ClosedSwarm saved) {if (_disposed) return false;+ if (saved.kind == 'devices' && !devicesEnabled) return false;final target = swarms.where((swarm) => swarm.id == saved.id).firstOrNull;if (target == null) return true;final present = {@@ -1401,6 +1408,275 @@ class AppNotifier extends ChangeNotifier {String? _pendingStoreHarness;+ bool get devicesEnabled =>+ ExperimentalFeature.devicesTab.available &&+ experimentalFeatures.isAvailable(ExperimentalFeature.devicesTab) &&+ experimentalFeatures.enabled(ExperimentalFeature.devicesTab);++ LocalKeyValueStore? get deviceLibraryStorage => _paneLayout?.storage;+ final deviceHosts = DeviceHosts();+ final _deviceReads = <String, Future<void>>{};++ void _syncDeviceHosts() {+ deviceHosts.reconcile([+ for (final machine in machineStates.values)+ if (!machine.machine.isShared)+ DeviceHost(+ id: machine.machine.machineId,+ name: machine.machine.displayName,+ local: machine.isLocalMachine,+ online:+ machine.connectionStatus == ConnectionStatus.connected &&+ !machine.isOffline &&+ !machine.needsLink,+ error: machine.needsLink+ ? 'Link this computer in Machines to manage its devices.'+ : null,+ ),+ ]);+ }++ /// Read each owned machine through its existing authenticated connection.+ /// Reading devices never opens a terminal or powers on a stopped machine.+ Future<void> refreshDevices() async {+ if (!devicesEnabled || _disposed) return;+ _syncDeviceHosts();+ if (_pool == null && connectionForTest == null) return;+ await Future.wait([+ for (final machine in machineStates.values.toList())+ if (!machine.machine.isShared &&+ !machine.isOffline &&+ !machine.needsLink)+ _readDeviceHost(machine),+ ]);+ }++ Future<void> _readDeviceHost(MachineState machine) {+ final id = machine.machine.machineId;+ final active = _deviceReads[id];+ if (active != null) return active;+ final account = currentUser?.id;+ final experimentAccount = experimentalFeatures.accountId;+ final revision = _authRevision;+ bool current() =>+ !_disposed &&+ devicesEnabled &&+ currentUser?.id == account &&+ experimentalFeatures.accountId == experimentAccount &&+ _authRevision == revision &&+ identical(machineStates[id], machine);+ late final Future<void> read;+ read =+ (() async {+ try {+ final connection = _conn(id);+ await connection.waitUntilReady(+ timeout: const Duration(seconds: 8),+ );+ if (!current()) return;+ final result = await connection.request(+ 'harness_devices_list',+ timeout: const Duration(seconds: 5),+ );+ if (!current() || machine.isOffline) return;+ _syncDeviceHosts();+ final status = result['status'];+ if (status is! Map<String, dynamic>) {+ throw const FormatException('Invalid device status');+ }+ deviceHosts.receive(+ id,+ DialStatus.fromJson(status),+ revision: result['revision'] is int+ ? result['revision'] as int+ : null,+ );+ } catch (error) {+ if (!current()) return;+ // Older local daemons already send addressed cable status. Never use+ // that fallback on a remote connection: dial_settings is local-only.+ if (error is WsRequestFailure &&+ error.code == 'UNSUPPORTED' &&+ machine.isLocalMachine &&+ dial.devices.isNotEmpty &&+ !machine.isOffline) {+ deviceHosts.receive(id, dial.status);+ } else {+ final unsupported =+ error is WsRequestFailure && error.code == 'UNSUPPORTED';+ deviceHosts.failed(+ id,+ unsupported+ ? 'Update Harness on ${machine.machine.displayName} to manage its devices.'+ : 'Couldn’t reach ${machine.machine.displayName}. Reconnect or refresh to try again.',+ );+ }+ }+ })().whenComplete(() {+ if (identical(_deviceReads[id], read)) _deviceReads.remove(id);+ });+ return _deviceReads[id] = read;+ }++ Future<bool> setHostDeviceSettings(+ String machineId,+ String id,+ Map<String, Object?> patch,+ ) async {+ final machine = machineStates[machineId];+ final host = deviceHosts.host(machineId);+ final target = host?.devices.where((d) => d.id == id).firstOrNull;+ if (!devicesEnabled ||+ machine == null ||+ machine.machine.isShared ||+ machine.isOffline ||+ machine.needsLink ||+ host?.online != true ||+ host?.available != true ||+ target?.attached != true ||+ target?.updating != null ||+ patch.isEmpty ||+ (_pool == null && connectionForTest == null)) {+ return false;+ }+ final account = currentUser?.id;+ try {+ final reply = await _conn(machineId).request(+ 'harness_device_settings',+ payload: {'id': id, 'patch': patch},+ timeout: const Duration(seconds: 6),+ );+ if (_disposed ||+ currentUser?.id != account ||+ !identical(machineStates[machineId], machine)) {+ return false;+ }+ if (reply['status'] case final Map<String, dynamic> status) {+ deviceHosts.receive(+ machineId,+ DialStatus.fromJson(status),+ revision: reply['revision'] is int ? reply['revision'] as int : null,+ );+ }+ return reply['ok'] == true;+ } on WsRequestFailure catch (failure) {+ if (failure.code == 'UNSUPPORTED' &&+ machine.isLocalMachine &&+ currentUser?.id == account) {+ return setDeviceSettings(id, patch);+ }+ return false;+ } catch (_) {+ return false;+ }+ }++ /// One utility tab for physical devices. The experiment must be explicitly+ /// acknowledged before any entry point, including restored history, opens it.+ void openDevices() {+ if (!devicesEnabled) return;+ final existing = swarms.where((s) => s.isDevices).firstOrNull;+ if (existing != null) {+ _ensureDevicesViewer(existing);+ selectSwarm(existing.id);+ return;+ }+ final current = activeSwarm;+ if (current.isEmptyStarter && !current.isUtility) {+ current+ ..kind = 'devices'+ ..name = Swarm.devicesName+ ..nameIsCustom = false+ ..isNewTabPage = false;+ _draftSwarmReturns.remove(current.id);+ _ensureDevicesViewer(current);+ _persistLayout();+ notifyListeners();+ return;+ }+ while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {+ _nextSwarmId++;+ }+ final tab = Swarm(+ id: 'swarm-${_nextSwarmId++}',+ name: Swarm.devicesName,+ kind: 'devices',+ );+ _ensureDevicesViewer(tab);+ swarms.add(tab);+ selectSwarm(tab.id);+ }++ void _devicesExperimentChanged() {+ if (devicesEnabled) return;+ final historyCount = _closedHistory.length;+ _closedHistory.removeWhere(+ (entry) => entry is ClosedSwarm && entry.kind == 'devices',+ );+ if (!swarms.any((s) => s.isDevices)) {+ if (historyCount != _closedHistory.length) notifyListeners();+ return;+ }+ final removed = swarms.where((s) => s.isDevices).toList();+ swarms.removeWhere((s) => s.isDevices);+ for (final tab in removed) {+ for (final pane in tab.panes) {+ if (!allPanes.contains(pane)) {+ unawaited(_detachSession(pane, sendClose: true));+ }+ }+ }+ if (swarms.isEmpty) swarms.add(Swarm(id: 'swarm-${_nextSwarmId++}'));+ if (!experimentalFeatures.loaded) {+ // Binding a different account hides its predecessor's page immediately,+ // before that account's workspace is ready to be persisted or attached.+ if (!swarms.any((s) => s.id == _activeSwarmId)) {+ _activeSwarmId = profileSwarms.first.id;+ }+ notifyListeners();+ return;+ }+ if (!swarms.any((s) => s.id == _activeSwarmId)) {+ selectSwarm(profileSwarms.first.id);+ } else {+ _persistLayout();+ notifyListeners();+ }+ }++ void _ensureDevicesViewer(Swarm tab) {+ if (!devicesEnabled || tab.panes.any((pane) => pane.isDevices)) return;+ final pane = TerminalPane(+ id: _nextPaneId++,+ machineId: '',+ kind: PaneKind.devices,+ );+ tab.panes.insert(0, pane);+ tab.focusedPaneId ??= pane.id;+ }++ Future<void> showDevicesTerminal(String machineId, String agentId) async {+ if (!devicesEnabled) return;+ final tab = swarms.where((tab) => tab.isDevices).firstOrNull;+ if (tab == null) return;+ _ensureDevicesViewer(tab);+ final viewer = tab.panes.firstWhere((pane) => pane.isDevices);+ viewer.machineId = machineId;+ viewer.ownerAgentId = agentId;+ tab.paneSizes.putIfAbsent(+ '2:manual',+ () => PaneArrangement.viewerBesideTerminal,+ );+ await assignAgentToPane(+ null,+ machineId,+ agentId,+ swarmId: tab.id,+ focus: false,+ intent: tab == activeSwarm ? AttachIntent.person : AttachIntent.automatic,+ );+ }+/// The companion's illustrated viewer and conversation, one per window./// Its panes are bound only after the account's experimental gate is loaded.void openCompanions() {@@ -1772,7 +2048,7 @@ class AppNotifier extends ChangeNotifier {final tab = activeSwarm;final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;if (pane == null) return Future.value();- if (tab.isCompanions) return requestCloseSwarm(tab.id);+ if (tab.isCompanions || tab.isDevices) return requestCloseSwarm(tab.id);final captured = tab.panes.where((p) =>@@ -2516,6 +2792,8 @@ class AppNotifier extends ChangeNotifier {// `this.` because the constructor's own parameter of the same name is in// scope here and is the nullable one.this.agentUnread.addListener(_announceUnreadToDial);+ experimentalFeatures.addListener(_devicesExperimentChanged);+ addListener(_syncDeviceHosts);}/// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.@@ -3068,20 +3346,27 @@ class AppNotifier extends ChangeNotifier {* was set on. Only the named fields go — absent means unchanged, so two windows open on one device* cannot overwrite each other with whatever each of them last saw.*- * Nothing is awaited and nothing is written here optimistically. The device answers with what it now- * HOLDS, which arrives as the next `dial_status`; that is also what corrects this window when the- * change was refused.+ * The return value confirms transport delivery only. Nothing is written here optimistically.+ * The device answers with what it now HOLDS, which arrives as the next `dial_status`; that is+ * also what corrects this window when the change was refused.*/- void setDeviceSettings(String id, Map<String, Object?> patch) {- if (patch.isEmpty) return;+ Future<bool> setDeviceSettings(String id, Map<String, Object?> patch) async {+ if (patch.isEmpty) return false;+ final target = dial.devices.where((device) => device.id == id).firstOrNull;+ if (target == null || !target.attached || target.updating != null) {+ return false;+ }final machineId = localMachineState?.machine.machineId;final connection = machineId == null ? null : _pool?[machineId];- if (connection == null) return;- final pending = connection.sendTerminalFrame('dial_settings', {- 'id': id,- ...patch,- });- unawaited(pending.catchError((_) => false));+ if (connection == null) return false;+ try {+ return await connection.sendTerminalFrame('dial_settings', {+ ...patch,+ 'id': id,+ });+ } catch (_) {+ return false;+ }}/// Tell the daemon which agents have a tile on the grid, so the dial can stay@@ -5221,6 +5506,7 @@ class AppNotifier extends ChangeNotifier {_clearMachineActivity(machine);if (machine.isLocalMachine) {machine.transportMode = MachineTransportMode.localOffline;+ dial.disconnect();}// Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open// terminal (if any) so the connected branch above can reattach it, for every machine — this@@ -8365,7 +8651,9 @@ class AppNotifier extends ChangeNotifier {Iterable<({String machineId, String agentId})> _visibleOnTab() {if (lifecycle() != AppLifecycleState.resumed) return const [];- if (activeSwarm.isStore || activeSwarm.isOrchestrator) return const [];+ if (activeSwarm.isStore || activeSwarm.isOrchestrator) {+ return const [];+ }return [for (final pane in activeSwarm.panes)if (zoomedPaneId == null || pane.id == zoomedPaneId)@@ -11976,7 +12264,10 @@ class AppNotifier extends ChangeNotifier {target.arranged = split.after;target.arrangedKey = key;}- if (firstAgent && !target.nameIsCustom && !target.isCompanions) {+ if (firstAgent &&+ !target.nameIsCustom &&+ !target.isCompanions &&+ !target.isDevices) {final agent = machine.agents.where((agent) => agent.id == agentId).firstOrNull;@@ -12614,7 +12905,7 @@ class AppNotifier extends ChangeNotifier {if (tab == null) return;final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;if (pane == null) return;- if (tab.isCompanions) {+ if (tab.isCompanions || tab.isDevices) {await closeSwarm(tab.id, persist: persist);return;}@@ -13403,6 +13694,11 @@ class AppNotifier extends ChangeNotifier {if (isStore && restored.any((s) => s.isStore)) continue;final isCompanions = raw['kind'] == 'companions';if (isCompanions && restored.any((s) => s.isCompanions)) continue;+ final isDevices = raw['kind'] == 'devices';+ if (isDevices &&+ (!devicesEnabled || restored.any((s) => s.isDevices))) {+ continue;+ }final swarm =Swarm(id: id,@@ -13417,6 +13713,8 @@ class AppNotifier extends ChangeNotifier {: Swarm.defaultName,kind: isStore? 'store'+ : isDevices+ ? 'devices': isCompanions? 'companions': raw['kind'] == 'orchestrator'@@ -13440,11 +13738,13 @@ class AppNotifier extends ChangeNotifier {(swarm.titleAgentId == null &&swarm.name != Swarm.defaultName &&!(swarm.isStore && swarm.name == Swarm.storeName) &&- !(swarm.isCompanions && swarm.name == Swarm.companionsName));+ !(swarm.isCompanions && swarm.name == Swarm.companionsName) &&+ !(swarm.isDevices && swarm.name == Swarm.devicesName));for (final item- in (swarm.isCompanions ? const [] : raw['panes'] as List).take(- maxPanes,- )) {+ in (swarm.isCompanions || swarm.isDevices+ ? const []+ : raw['panes'] as List)+ .take(maxPanes)) {final entry = PaneLayoutEntry.fromJson(item);if (entry == null) continue;final key = '${entry.machineId}\u0000${entry.agentId}';@@ -13495,6 +13795,7 @@ class AppNotifier extends ChangeNotifier {}}swarm.paneSizes.addAll(PaneArrangement.readSaved(raw['paneSizes']));+ if (swarm.isDevices) _ensureDevicesViewer(swarm);restored.add(swarm);}if (restored.isNotEmpty) {@@ -14218,7 +14519,23 @@ class AppNotifier extends ChangeNotifier {case 'dial_status':// The dial came, went, or started taking an update. Its own notifier —// see [dial] — so nothing else in the window rebuilds for it.+ if (!machine.isLocalMachine) return;dial.apply(DialStatus.fromJson(payload));+ _syncDeviceHosts();+ deviceHosts.receive(machineId, dial.status);+ return;+ case 'harness_devices_changed':+ if (machine.machine.isShared) return;+ if (payload['status'] case final Map<String, dynamic> status) {+ _syncDeviceHosts();+ deviceHosts.receive(+ machineId,+ DialStatus.fromJson(status),+ revision: payload['revision'] is int+ ? payload['revision'] as int+ : null,+ );+ }return;case 'dial_scroll':// Straight through, including the reports carrying no travel — the ends of a stroke are the point@@ -14839,6 +15156,7 @@ class AppNotifier extends ChangeNotifier {}_closeOwnerMemories();experimentalFeatures.dispose();+ deviceHosts.dispose();viewer?.auth.dispose();_deviceVisit?.dispose();_modelManager?.dispose();diff --git a/desktop/lib/state/dial_status.dart b/desktop/lib/state/dial_status.dartindex 9a53c88db..0503ac025 100644--- a/desktop/lib/state/dial_status.dart+++ b/desktop/lib/state/dial_status.dart@@ -45,6 +45,22 @@ class DeviceSettings {final int? companionProtocol;final DialCompanion? companionDetails;+ /// Last-reported values for the local device library. Restoring these never+ /// marks a device connected or sends settings back to it.+ Map<String, Object?> toJson() => {+ 'brightness': brightness,+ 'character': character,+ 'face': face,+ 'muted': muted,+ 'quiet': quiet,+ 'straightTitle': straightTitle,+ 'focusFace': focusFace,+ 'scrollReversed': scrollReversed,+ 'round': round,+ 'voiceLang': voiceLang,+ if (followCompanion != null) 'followCompanion': followCompanion,+ };+/// Read with `is`, never `as`, and refused whole when a field is missing: a default here is a value/// this window invented, and the pane would then offer a setting the device does not have.static DeviceSettings? fromJson(Object? value) {@@ -268,4 +284,26 @@ class DialState extends ChangeNotifier {}notifyListeners();}++ /// A lost host connection cannot leave USB controls writable. Retain the+ /// last readings until the daemon greets this window again.+ void disconnect() {+ if (!status.attached && !devices.any((d) => d.attached)) return;+ apply(+ DialStatus(+ attached: false,+ devices: [+ for (final device in devices)+ DialStatus(+ attached: false,+ id: device.id,+ mac: device.mac,+ fw: device.fw,+ hw: device.hw,+ settings: device.settings,+ ),+ ],+ ),+ );+ }}diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex 5f453ea97..2ce318dfc 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -20,7 +20,8 @@ class Swarm {nameIsCustom ??(normalizeName(name) != defaultName &&!(kind == 'store' && name == storeName) &&- !(kind == 'companions' && name == companionsName));+ !(kind == 'companions' && name == companionsName) &&+ !(kind == 'devices' && name == devicesName));/// What the tab holds: `harness` — panes of agents (the default); `store` —/// the Harness Store, no panes. A store tab is a tab like any other —@@ -35,7 +36,8 @@ class Swarm {isNewTabPage && kind == 'harness' && panes.isEmpty && presets.isEmpty;bool get isStore => kind == 'store';bool get isCompanions => kind == 'companions';- bool get isUtility => isStore || isCompanions;+ bool get isDevices => kind == 'devices';+ bool get isUtility => isStore || isCompanions || isDevices;bool get isOrchestrator =>kind == 'orchestrator' &&orchestratorId != null &&@@ -43,6 +45,7 @@ class Swarm {String? orchestratorId, orchestratorMachineId;static const storeName = 'Harness Store';static const companionsName = 'Companions';+ static const devicesName = 'Devices';static const defaultName = 'New Tab';// 'New Harness' was the default until 2026-09-15, 'New Agent' for a daydiff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dartindex 6652d17be..b703fac37 100644--- a/desktop/lib/state/terminal_pane.dart+++ b/desktop/lib/state/terminal_pane.dart@@ -10,9 +10,9 @@ import '../core/models.dart' show SharedHarness;/// terminal. It is DERIVED from the agent (the daemon says where the viewer/// is, and the tile follows) and never persisted: a restored layout re-opens/// it from the agent's next frame, so a stale URL from a previous run can-/// never be loaded. [companion] is the built-in native viewer, derived from-/// the selected individual only after its account's experiment is enabled.-enum PaneKind { terminal, web, companion }+/// never be loaded. [companion] and [devices] are built-in native DSH viewers,+/// derived only after their account's experiment is enabled.+enum PaneKind { terminal, web, companion, devices }/// One tile in the terminal grid.///@@ -40,7 +40,8 @@ class TerminalPane {final PaneKind kind;bool get isWeb => kind == PaneKind.web;bool get isCompanion => kind == PaneKind.companion;- bool get isViewer => isWeb || isCompanion;+ bool get isDevices => kind == PaneKind.devices;+ bool get isViewer => isWeb || isCompanion || isDevices;/// [PaneKind.web] only: what the tile loads. Changes when the agent's frame/// names a new viewer URL; the panel navigates rather than remounts.diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dartindex 7d0535777..3cfba92f7 100644--- a/desktop/lib/state/workspace_status.dart+++ b/desktop/lib/state/workspace_status.dart@@ -12,6 +12,7 @@ import 'terminal_pane.dart';String tabHarnessType(AppNotifier app, Swarm tab) {if (tab.isStore) return 'store';if (tab.isCompanions) return 'companions';+ if (tab.isDevices) return 'devices';if (tab.isOrchestrator) return 'orchestrator';final counts = <String, int>{};for (final pane in tab.panes) {@@ -105,6 +106,8 @@ Map<String, String> workspaceTabNames(AppNotifier app) {? 'store': tab.isCompanions? 'companions'+ : tab.isDevices+ ? Swarm.devicesName: tab.isOrchestrator? 'orchestrator': candidates[tab.id]!.isEmptydiff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex c1856e67e..ec650fdb8 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -56,6 +56,7 @@ class PaneGrid extends StatelessWidget {this.onSplitPane,this.soloFocused = false,this.companionViewer,+ this.devicesViewer,});final AppNotifier notifier;@@ -72,6 +73,7 @@ class PaneGrid extends StatelessWidget {/// The built-in companion DSH viewer; its agent uses the ordinary terminal.final WidgetBuilder? companionViewer;+ final WidgetBuilder? devicesViewer;@overrideWidget build(BuildContext context) {@@ -88,6 +90,7 @@ class PaneGrid extends StatelessWidget {onSplitPane: onSplitPane,soloFocused: soloFocused,companionViewer: companionViewer,+ devicesViewer: devicesViewer,);}final panes = notifier.panes;@@ -105,6 +108,7 @@ class PaneGrid extends StatelessWidget {onOpenModels: onOpenModels,onSplitPane: onSplitPane,companionViewer: companionViewer,+ devicesViewer: devicesViewer,);final cells = <Widget>[for (final pane in visible) cell(pane),@@ -255,6 +259,7 @@ class _SwarmCanvas extends StatefulWidget {this.onSplitPane,this.soloFocused = false,this.companionViewer,+ this.devicesViewer,});final AppNotifier notifier;final AgentDragRef? dragging;@@ -264,6 +269,7 @@ class _SwarmCanvas extends StatefulWidget {final void Function(int paneId, PaneResizeAxis axis)? onSplitPane;final bool soloFocused;final WidgetBuilder? companionViewer;+ final WidgetBuilder? devicesViewer;@overrideState<_SwarmCanvas> createState() => _SwarmCanvasState();}@@ -603,6 +609,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {onSplitPane: widget.onSplitPane,solo: widget.soloFocused,companionViewer: widget.companionViewer,+ devicesViewer: widget.devicesViewer,),),),@@ -1204,6 +1211,7 @@ class _PaneCell extends StatelessWidget {this.onSplitPane,this.solo = false,this.companionViewer,+ this.devicesViewer,});final AppNotifier notifier;@@ -1215,6 +1223,7 @@ class _PaneCell extends StatelessWidget {onOpenModels;final void Function(int paneId, PaneResizeAxis axis)? onSplitPane;final WidgetBuilder? companionViewer;+ final WidgetBuilder? devicesViewer;/// Drawn alone under [PaneGrid.soloFocused]: it reads as the only view — no/// dimming or zoom, since it already fills the screen. The focused rim still@@ -1321,7 +1330,10 @@ class _PaneCell extends StatelessWidget {opacity: inFlight?.paneId == pane.id ? 0.35 : 1,child: child,),- child: pane.isCompanion+ child: pane.isDevices+ ? devicesViewer?.call(context) ??+ const SizedBox.shrink()+ : pane.isCompanion? companionViewer?.call(context) ??const SizedBox.shrink(): _PaneContent(@@ -2030,6 +2042,7 @@ class _SwapZone extends StatelessWidget {// underneath keeps every click the rest of the time.ignoring:notifier.activeSwarm.isCompanions ||+ notifier.activeSwarm.isDevices ||dragging == null ||dragging.paneId == paneId,child: DragTarget<PaneDragRef>(@@ -2274,7 +2287,10 @@ class _DropZone extends StatelessWidget {child,Positioned.fill(child: IgnorePointer(- ignoring: notifier.activeSwarm.isCompanions || dragging == null,+ ignoring:+ notifier.activeSwarm.isCompanions ||+ notifier.activeSwarm.isDevices ||+ dragging == null,child: DragTarget<AgentDragRef>(onAcceptWithDetails: (details) => notifier.assignAgentToPane(paneId,diff --git a/desktop/lib/widgets/workspace_store_button.dart b/desktop/lib/widgets/workspace_store_button.dartindex ceb326df5..bb796d168 100644--- a/desktop/lib/widgets/workspace_store_button.dart+++ b/desktop/lib/widgets/workspace_store_button.dart@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;import '../store/store_mark.dart';+import '../shared/theme/app_icons.dart';import 'desktop_chrome.dart';import 'workspace_bar_control.dart';@@ -14,15 +15,20 @@ class WorkspaceStoreButton extends StatelessWidget {required this.width,required this.tooltip,this.onPressed,+ this.devices = false,});final double width;final String tooltip;final VoidCallback? onPressed;+ final bool devices;- static Size _labelSize(BuildContext context) {+ static Size _labelSize(BuildContext context, {bool devices = false}) {final painter = TextPainter(- text: TextSpan(text: 'Harness Store', style: DesktopChrome.control()),+ text: TextSpan(+ text: devices ? 'Devices' : 'Harness Store',+ style: DesktopChrome.control(),+ ),textDirection: Directionality.of(context),textScaler: MediaQuery.textScalerOf(context),maxLines: 1,@@ -32,7 +38,8 @@ class WorkspaceStoreButton extends StatelessWidget {return size;}- static double widthOf(BuildContext context) => _labelSize(context).width + 52;+ static double widthOf(BuildContext context, {bool devices = false}) =>+ _labelSize(context, devices: devices).width + 52;@overrideWidget build(BuildContext context) {@@ -40,14 +47,14 @@ class WorkspaceStoreButton extends StatelessWidget {final enabled = onPressed != null;final accent = grid.AppPalette.swarmAccent;return WorkspaceBarControl(- label: 'Harness Store',+ label: devices ? 'Devices' : 'Harness Store',tooltip: tooltip,onPressed: onPressed,builder: (context, emphasized) => Container(width: width,height: math.max(grid.AppControl.heightSmall,- _labelSize(context).height + 12,+ _labelSize(context, devices: devices).height + 12,),padding: const EdgeInsets.symmetric(horizontal: 12),decoration: ShapeDecoration(@@ -70,11 +77,18 @@ class WorkspaceStoreButton extends StatelessWidget {),child: Row(children: [- StoreMark(enabled: enabled),+ if (devices)+ Icon(+ AppIcons.circle,+ size: 16,+ color: accent.withValues(alpha: enabled ? 1 : .45),+ )+ else+ StoreMark(enabled: enabled),const SizedBox(width: 8),Expanded(child: Text(- 'Harness Store',+ devices ? 'Devices' : 'Harness Store',maxLines: 1,overflow: TextOverflow.ellipsis,style: DesktopChrome.control(diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 020542e5d..f5956d046 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -128,7 +128,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}private func sendTabAction(_ method: String, arguments: Any?) {- guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "resourceMonitor", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "openStatusHarness", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {+ guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "resourceMonitor", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "openStatusHarness", "store", "devices", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {channel.invokeMethod(method, arguments: arguments)return}@@ -1007,6 +1007,7 @@ private class SwarmPlainIconButton: SwarmIconButton {/// A quiet filled pill, with the Store's colorful mark as its focal point./// Drawing the content keeps the same spacing across AppKit button styles.private final class SwarmStoreButton: SwarmIconButton {+ var monochrome = falsevar palette = SwarmNativePalette() { didSet { needsDisplay = true } }var preferredWidth: CGFloat {ceil(workspaceBarTextWidth(title,@@ -1024,9 +1025,16 @@ private final class SwarmStoreButton: SwarmIconButton {palette.accent.withAlphaComponent(hasKeyboardFocus && isEnabled ? 0.85 : 0.12).setStroke()shape.lineWidth = hasKeyboardFocus && isEnabled ? 1.5 : 1shape.stroke()- image?.draw(in: NSRect(x: 12, y: (bounds.height - 16) / 2, width: 16, height: 16),+ let iconRect = NSRect(x: 12, y: (bounds.height - 16) / 2, width: 16, height: 16)+ NSGraphicsContext.current?.cgContext.beginTransparencyLayer(auxiliaryInfo: nil)+ image?.draw(in: iconRect,from: .zero, operation: .sourceOver, fraction: isEnabled ? 1 : 0.45,respectFlipped: true, hints: [.interpolation: NSImageInterpolation.high])+ if monochrome {+ palette.accent.setFill()+ iconRect.fill(using: .sourceIn)+ }+ NSGraphicsContext.current?.cgContext.endTransparencyLayer()let paragraph = NSMutableParagraphStyle()paragraph.lineBreakMode = .byTruncatingTaillet attributes: [NSAttributedString.Key: Any] = [@@ -1783,6 +1791,7 @@ private final class SwarmTabStrip: NSView {fileprivate let shareButton = SwarmShareButton()fileprivate let searchButton = SwarmPlainIconButton()fileprivate let storeButton = SwarmStoreButton()+ fileprivate let devicesButton = SwarmStoreButton()private var shareTarget: [String: Any]?private var barFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)private var resourceGroupGapCells: CGFloat = 2.5@@ -1899,6 +1908,20 @@ private final class SwarmTabStrip: NSView {searchButton.action = #selector(openSearch)searchButton.setAccessibilityLabel("Open Harness")addSubview(searchButton)+ devicesButton.isBordered = false+ devicesButton.title = "Devices"+ devicesButton.font = navigationFont+ devicesButton.palette = palette+ devicesButton.image = HarnessControlSymbols.image("circle")+ devicesButton.monochrome = true+ devicesButton.isEnabled = false+ devicesButton.isHidden = true+ devicesButton.focusRingType = .none+ devicesButton.target = self+ devicesButton.action = #selector(openDevices)+ devicesButton.toolTip = "Manage Harness devices"+ devicesButton.setAccessibilityLabel("Devices")+ addSubview(devicesButton)storeButton.isBordered = falsestoreButton.title = "Harness Store"storeButton.font = navigationFont@@ -2026,6 +2049,7 @@ private final class SwarmTabStrip: NSView {NSApp.appearance = NSAppearance(named: palette.dark ? .darkAqua : .aqua)storeButton.palette = palettenewButton.contentTintColor = palette.accent+ devicesButton.palette = palettenewButton.foreground = palette.navigationForegroundfor tab in tabs {tab.palette = palette@@ -2044,8 +2068,11 @@ private final class SwarmTabStrip: NSView {statusBar.isHidden = (state["tabs"] as? [Any])?.isEmpty != false || state["footerCovered"] as? Bool == truelet passiveFooter = state["footerPassive"] as? Bool == truestatusBar.setAccessibilityHidden(passiveFooter || statusBar.isHidden)+ devicesButton.isHidden = state["devicesVisible"] as? Bool != true+ devicesButton.setAccessibilityHidden(devicesButton.isHidden)setAccessibilityChildren(- [scroll, newButton, searchButton, storeButton] ++ [scroll, newButton, searchButton] ++ (devicesButton.isHidden ? [] : [devicesButton]) + [storeButton] +(statusBar.isHidden || passiveFooter ? [] : [statusBar]))reduceMotion = state["reduceMotion"] as? Bool == trueif let style = state["barStyle"] as? [String: Any] {@@ -2063,6 +2090,7 @@ private final class SwarmTabStrip: NSView {}storeButton.font = navigationFontstoreButton.isEnabled = actionsEnabled+ devicesButton.isEnabled = actionsEnabled && !devicesButton.isHiddensearchButton.foreground = palette.navigationForegroundsearchButton.isEnabled = actionsEnabledsearchButton.toolTip = state["searchTooltip"] as? String ?? "Open Harness"@@ -2288,7 +2316,11 @@ private final class SwarmTabStrip: NSView {storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth,y: (bounds.height - toolHeight) / 2, width: storeWidth, height: toolHeight)let iconWidth = cell * 4- searchButton.frame = NSRect(x: storeButton.frame.minX - iconWidth - 8,+ let devicesWidth = devicesButton.isHidden ? 0 : devicesButton.preferredWidth+ devicesButton.frame = NSRect(x: storeButton.frame.minX - devicesWidth - 8,+ y: (bounds.height - toolHeight) / 2, width: devicesWidth, height: toolHeight)+ let searchEdge = devicesButton.isHidden ? storeButton.frame.minX : devicesButton.frame.minX+ searchButton.frame = NSRect(x: searchEdge - iconWidth - 8,y: (bounds.height - toolHeight) / 2, width: iconWidth, height: toolHeight)// Only navigation actions share the tab row. Context has the full footer.let tabBudget = max(0, searchButton.frame.minX - cell * 6)@@ -2416,6 +2448,10 @@ private final class SwarmTabStrip: NSView {@objc private func openStore() {if actionsEnabled && storeButton.isEnabled { emit?("store", nil) }}++ @objc private func openDevices() {+ if actionsEnabled && devicesButton.isEnabled && !devicesButton.isHidden { emit?("devices", nil) }+ }@objc private func openFocusedPullRequest() {if actionsEnabled && pullRequestButton.isEnabled, let url = pullRequestButton.actionURL {emit?("focusedPullRequest", ["url": url])diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex ba278c9dc..fa3799b98 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -148,6 +148,7 @@ flutter:- assets/model-icons/- assets/octicons/- assets/harness_device_studio.jpg+ - assets/devices/- assets/harness_store_card.jpg- assets/swarm-wallpapers/diff --git a/desktop/scripts/build-devices-review.sh b/desktop/scripts/build-devices-review.shnew file mode 100644index 000000000..115896f70--- /dev/null+++ b/desktop/scripts/build-devices-review.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+# Separate, disposable review app. The regular build keeps its default-off gate.+set -euo pipefail+DEVICES_DESKTOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+DEVICES_REVIEW="$DEVICES_DESKTOP_DIR/build/devices-review/Devices Review.app"++cd "$DEVICES_DESKTOP_DIR"+bash scripts/build-macos-debug.sh --no-pub --target tool/devices_preview.dart \+ --dart-define=HARNESS_TEST=true --dart-define=DEVICES_REVIEW=true+mkdir -p "$(dirname "$DEVICES_REVIEW")"+ditto build/macos/Build/Products/Debug/Harness.app "$DEVICES_REVIEW"+/usr/libexec/PlistBuddy -c 'Set :CFBundleIdentifier ai.autonomous.harness.devices-review.combined' "$DEVICES_REVIEW/Contents/Info.plist"+/usr/libexec/PlistBuddy -c 'Set :CFBundleName Devices Review' "$DEVICES_REVIEW/Contents/Info.plist"+codesign --force --sign - \+ --preserve-metadata=entitlements,requirements,flags,runtime "$DEVICES_REVIEW"+codesign --verify --deep --strict "$DEVICES_REVIEW"+# Fixture builds replace Harness.app; always leave the normal entrypoint built.+bash scripts/build-macos-debug.sh --no-pub --target lib/main.dart+echo "Devices review ready: $DEVICES_REVIEW"diff --git a/desktop/test/devices_controller_test.dart b/desktop/test/devices_controller_test.dartnew file mode 100644index 000000000..ece5358b7--- /dev/null+++ b/desktop/test/devices_controller_test.dart@@ -0,0 +1,267 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/devices/devices_controller.dart';+import 'package:harness/state/dial_status.dart';++import 'swarm_state_test.dart' show MemoryStore;++DialStatus deviceStatus(+ String id, {+ String? mac,+ bool attached = true,+ int brightness = 80,+ bool muted = true,+ String? updating,+}) => DialStatus.fromJson({+ 'id': id,+ 'mac': mac ?? '00:11:22:33:$id',+ 'attached': attached,+ 'fw': '0.0.101',+ 'updating': updating,+ 'settings': {+ 'brightness': brightness,+ 'character': 2,+ 'face': 466,+ 'round': true,+ 'muted': muted,+ 'quiet': false,+ 'straightTitle': true,+ 'focusFace': false,+ 'scrollReversed': false,+ 'voiceLang': 'en',+ },+});++void report(DialState dial, List<DialStatus> devices) => dial.apply(+ DialStatus(attached: devices.any((d) => d.attached), devices: devices),+);++void main() {+ test(+ 'reusing a USB port for a different MAC keeps two distinct devices',+ () async {+ final dial = DialState();+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ sendSettings: (_, _) async => true,+ );+ await controller.load();+ report(dial, [deviceStatus('port', mac: 'aa:aa')]);+ final first = controller.devices.single.key;+ controller.rename(first, 'Studio', HarnessDeviceModel.pro);+ report(dial, [deviceStatus('port', mac: 'bb:bb')]);+ expect(controller.devices, hasLength(2));+ expect(controller.device(first)!.status.attached, isFalse);+ expect(controller.devices.last.name, isNot('Studio'));+ controller.dispose();+ dial.dispose();+ },+ );++ test('a failed library read cannot overwrite saved devices; retry merges new arrivals', () async {+ final storage = _ReadFailureStore();+ final dial = DialState();+ final first = DevicesController(+ dial: dial,+ accountId: 'a',+ storage: storage,+ sendSettings: (_, _) async => true,+ );+ await first.load();+ report(dial, [deviceStatus('old')]);+ first.rename(+ first.devices.single.key,+ 'Saved device',+ HarnessDeviceModel.pro,+ );+ await first.settled;+ first.dispose();+ final saved = storage.values.values.single;+ storage.fail = true;+ report(dial, [deviceStatus('new')]);+ final next = DevicesController(+ dial: dial,+ accountId: 'a',+ storage: storage,+ sendSettings: (_, _) async => true,+ );+ await next.load();+ await next.settled;+ expect(next.error, isNotNull);+ expect(storage.values.values.single, saved);+ storage.fail = false;+ await next.retrySave();+ await next.settled;+ expect(next.devices, hasLength(2));+ expect(next.devices.any((d) => d.name == 'Saved device'), isTrue);+ expect(next.error, isNull);+ next.dispose();+ dial.dispose();+ });++ test('five devices retain individual names, models and readings across reconnect and restart', () async {+ final storage = MemoryStore();+ final dial = DialState();+ final sent = <String>[];+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ storage: storage,+ sendSettings: (id, patch) async {+ sent.add(id);+ return true;+ },+ );+ await controller.load();+ report(dial, [for (var i = 0; i < 5; i++) deviceStatus('$i')]);+ for (var i = 0; i < 5; i++) {+ controller.rename(+ controller.devices[i].key,+ 'Desk $i',+ i < 2 ? HarnessDeviceModel.harness : HarnessDeviceModel.pro,+ );+ }+ expect(+ controller.devices.where((d) => d.model == HarnessDeviceModel.pro),+ hasLength(3),+ );+ final key = controller.devices.last.key;+ // Same hardware moved to a different USB port keeps its saved identity.+ report(dial, [+ deviceStatus('new-port', mac: '00:11:22:33:4', brightness: 35),+ ]);+ expect(controller.devices, hasLength(5));+ expect(controller.device(key)!.name, 'Desk 4');+ expect(controller.device(key)!.status.id, 'new-port');+ expect(controller.devices.where((d) => d.status.attached), hasLength(1));+ await controller.settled;+ controller.dispose();+ dial.apply(DialStatus.none);+ final restored = DevicesController(+ dial: dial,+ accountId: 'a',+ storage: storage,+ sendSettings: (_, _) async => true,+ );+ await restored.load();+ expect(restored.devices, hasLength(5));+ expect(restored.devices.every((d) => !d.canEdit), isTrue);+ expect(restored.device(key)!.status.settings!.brightness, 35);+ expect(+ sent,+ isEmpty,+ reason: 'Discovery and restoration never apply settings',+ );+ final other = DevicesController(+ dial: dial,+ accountId: 'b',+ storage: storage,+ sendSettings: (_, _) async => true,+ );+ await other.load();+ expect(other.devices, isEmpty);+ restored.dispose();+ other.dispose();+ dial.dispose();+ });++ test('patches address one device and values change only when that device acknowledges', () async {+ final dial = DialState();+ final sent = <(String, Map<String, Object?>)>[];+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ sendSettings: (id, patch) async {+ sent.add((id, patch));+ return true;+ },+ );+ await controller.load();+ report(dial, [deviceStatus('a'), deviceStatus('b')]);+ final key = controller.devices.last.key;+ await controller.update(key, {'muted': false});+ expect(sent, hasLength(1));+ expect(sent.single.$1, 'b');+ expect(sent.single.$2, {'muted': false});+ expect(controller.saving(key), isTrue);+ expect(controller.device(key)!.status.settings!.muted, isTrue);+ report(dial, [deviceStatus('a', muted: false), deviceStatus('b')]);+ expect(+ controller.saving(key),+ isTrue,+ reason: 'Another device cannot acknowledge this write',+ );+ report(dial, [deviceStatus('b', muted: false), deviceStatus('a')]);+ expect(controller.saving(key), isFalse);+ expect(controller.device(key)!.status.settings!.muted, isFalse);+ report(dial, [deviceStatus('b', attached: false), deviceStatus('a')]);+ await controller.update(key, {'brightness': 15});+ expect(sent, hasLength(1));+ report(dial, [deviceStatus('b', updating: '0.0.102')]);+ await controller.update(key, {'brightness': 15});+ expect(sent, hasLength(1));+ controller.dispose();+ dial.dispose();+ });++ testWidgets(+ 'unconfirmed and disconnected writes recover without optimistic settings',+ (tester) async {+ final dial = DialState();+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ confirmationTimeout: const Duration(seconds: 2),+ sendSettings: (_, _) async => true,+ );+ await controller.load();+ report(dial, [deviceStatus('a')]);+ final key = controller.devices.single.key;+ await controller.update(key, {'brightness': 15});+ await tester.pump(const Duration(seconds: 2));+ expect(controller.deviceError(key), contains('wasn’t confirmed'));+ expect(controller.device(key)!.status.settings!.brightness, 80);+ await controller.update(key, {'brightness': 25});+ expect(controller.deviceError(key), isNull);+ dial.disconnect();+ expect(controller.deviceError(key), contains('disconnected'));+ expect(controller.saving(key), isFalse);+ controller.dispose();+ dial.dispose();+ },+ );++ test('a late transport failure cannot cancel a newer write', () async {+ final dial = DialState();+ final first = Completer<bool>();+ var calls = 0;+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ sendSettings: (_, _) => ++calls == 1 ? first.future : Future.value(true),+ );+ await controller.load();+ report(dial, [deviceStatus('a')]);+ final key = controller.devices.single.key;+ final old = controller.update(key, {'brightness': 20});+ report(dial, [deviceStatus('a', brightness: 20)]);+ await controller.update(key, {'brightness': 40});+ first.complete(false);+ await old;+ expect(controller.saving(key), isTrue);+ expect(controller.deviceError(key), isNull);+ controller.dispose();+ dial.dispose();+ });+}++class _ReadFailureStore extends MemoryStore {+ bool fail = false;+ @override+ Future<String?> read(String key) async {+ if (fail) throw StateError('Read unavailable');+ return super.read(key);+ }+}diff --git a/desktop/test/devices_harness_test.dart b/desktop/test/devices_harness_test.dartnew file mode 100644index 000000000..e73e82749--- /dev/null+++ b/desktop/test/devices_harness_test.dart@@ -0,0 +1,124 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/engine_availability.dart';+import 'package:harness/core/models.dart';+import 'package:harness/devices/devices_harness_controller.dart';+import 'package:harness/settings/experimental_features.dart';+import 'package:harness/state/app_state.dart';++import 'experimental_features_test.dart' show AccountSettings;+import 'support/model_manager.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late ModelManagerConnection connection;+ late ModelManagerTestApp app;+ late DevicesHarnessController devices;+ setUp(() async {+ connection = ModelManagerConnection();+ app = ModelManagerTestApp(connection);+ app.stateOf('m')!.engines.replace([+ const EngineAvailability(engine: 'codex', installed: true),+ ]);+ app.currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ );+ app.experimentalFeatures.bind('a', transport: AccountSettings('a'));+ await app.experimentalFeatures.refresh();+ await app.experimentalFeatures.set(ExperimentalFeature.devicesTab, true);+ app.openDevices();+ devices = DevicesHarnessController(app);+ });+ tearDown(() {+ devices.dispose();+ app.dispose();+ });++ test(+ 'waits for the existing inventory before deciding to create a conversation',+ () async {+ final loading = Completer<void>();+ final owner = app.stateOf('m')!;+ owner.agentLoadStatus = AgentLoadStatus.loading;+ owner.agentsLoadInFlight = loading.future;+ final opening = devices.open();+ expect(connection.creations, isEmpty);+ owner.agents = [+ const Agent(+ id: 'previous',+ name: 'Devices',+ engine: 'codex',+ dsh: devicesHarnessId,+ terminalAvailable: true,+ ),+ ];+ owner.agentLoadStatus = AgentLoadStatus.loaded;+ loading.complete();+ await opening;+ expect(connection.creations, isEmpty);+ expect(app.panes.any((pane) => pane.agentId == 'previous'), isTrue);+ },+ );++ test(+ 'opens the bundled DSH beside its dashboard and reuses its conversation',+ () async {+ await devices.open();+ expect(devices.error, isNull);+ expect(+ connection.creations.single,+ containsPair('dsh', devicesHarnessId),+ );+ expect(+ connection.creations.single,+ containsPair('bypassPermission', false),+ );+ expect(connection.creations.single['prompt'], isNull);+ expect(app.activeSwarm.name, 'Devices');+ expect(app.panes.where((pane) => pane.isDevices), hasLength(1));+ expect(+ app.panes.where((pane) => pane.agentId == 'manager'),+ hasLength(1),+ );+ await devices.open();+ expect(connection.creations, hasLength(1));+ expect(app.panes, hasLength(2));+ },+ );+ test(+ 'concurrent opens and an ambiguous creation reuse one durable request',+ () async {+ connection.holdCreation = Completer<void>();+ connection.loseFirstReply = true;+ final first = devices.open();+ expect(identical(first, devices.open()), isTrue);+ connection.holdCreation!.complete();+ await first;+ expect(devices.error, isNotNull);+ await devices.open();+ expect(devices.error, isNull);+ expect(connection.creations, hasLength(1));+ expect(app.panes, hasLength(2));+ },+ );+ test(+ 'an account switch during creation cannot attach the old conversation',+ () async {+ connection.holdCreation = Completer<void>();+ final opening = devices.open();+ await Future<void>.delayed(Duration.zero);+ app.currentUser = const CurrentUserProfile(+ id: 'b',+ email: '[email protected]',+ );+ connection.holdCreation!.complete();+ await opening;+ expect(app.swarms.any((tab) => tab.isDevices), isFalse);+ expect(app.allPanes.where((pane) => pane.agentId == 'manager'), isEmpty);+ await devices.open();+ expect(connection.creations.length, lessThanOrEqualTo(1));+ },+ );+}diff --git a/desktop/test/devices_hosts_test.dart b/desktop/test/devices_hosts_test.dartnew file mode 100644index 000000000..a3ba8d6c8--- /dev/null+++ b/desktop/test/devices_hosts_test.dart@@ -0,0 +1,271 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/devices/device_hosts.dart';+import 'package:harness/devices/devices_controller.dart';+import 'package:harness/settings/experimental_features.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/dial_status.dart';+import 'package:harness/ws/ws_conn.dart';++import 'devices_controller_test.dart' show deviceStatus;+import 'experimental_features_test.dart' show AccountSettings;+import 'swarm_state_test.dart' show MemoryStore, createApp;++class _DeviceConnection extends WsConn {+ _DeviceConnection(String id)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: id,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final requests = <(String, Map<String, dynamic>)>[];+ DialStatus device = deviceStatus('same-usb-id');+ int revision = 1;+ Completer<Map<String, dynamic>>? held;+ bool unsupported = false;+ Map<String, dynamic> get snapshot => {+ 'revision': revision,+ 'status': {+ 'attached': device.attached,+ 'devices': [+ {+ 'id': device.id,+ 'mac': device.mac,+ 'attached': device.attached,+ 'settings': device.settings!.toJson(),+ },+ ],+ },+ };+ @override+ Future<void> waitUntilReady({+ Duration timeout = const Duration(seconds: 20),+ }) async {}+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ requests.add((type, payload));+ if (unsupported) {+ throw WsRequestFailure(+ responseType: '${type}_result',+ code: 'UNSUPPORTED',+ );+ }+ if (type == 'harness_devices_list') return held?.future ?? snapshot;+ if (type == 'harness_device_settings') {+ expect(payload['id'], device.id);+ device = DialStatus.fromJson({+ 'id': device.id,+ 'mac': device.mac,+ 'attached': true,+ 'settings': {...device.settings!.toJson(), ...payload['patch'] as Map},+ });+ revision++;+ return {'ok': true, ...snapshot};+ }+ return {};+ }+}++void main() {+ test('account devices discover and address the right owned host; offline and shared hosts are read-only', () async {+ final connections = {+ for (final id in ['m', 'remote']) id: _DeviceConnection(id),+ };+ final storage = MemoryStore();+ final app = createApp(+ store: storage,+ connected: true,+ connectionForTest: (id) => connections[id]!,+ );+ addTearDown(app.dispose);+ app.machineStates['m']!.localOnly = true;+ for (final id in ['remote', 'offline', 'shared']) {+ final machine = Machine(+ machineId: id,+ authMode: MachineAuthMode.remote,+ name: '$id computer',+ isShared: id == 'shared',+ );+ app.machineStates[id] = MachineState(machine)+ ..nodeOnline = id != 'offline'+ ..connectionStatus = id == 'offline'+ ? ConnectionStatus.disconnected+ : ConnectionStatus.connected;+ }+ app.experimentalFeatures.bind('a', transport: AccountSettings('a'));+ await app.experimentalFeatures.refresh();+ await app.experimentalFeatures.set(ExperimentalFeature.devicesTab, true);+ final controller = DevicesController(+ hosts: app.deviceHosts,+ accountId: 'a',+ storage: storage,+ sendHostSettings: app.setHostDeviceSettings,+ );+ addTearDown(controller.dispose);+ await controller.load();+ await app.refreshDevices();+ expect(controller.devices, hasLength(2));+ expect(+ controller.devices.map((d) => d.key).toSet(),+ hasLength(2),+ reason: 'Even identical USB ids and MACs on two computers stay separate',+ );+ final local = controller.devices.firstWhere((d) => d.machineId == 'm');+ final remote = controller.devices.firstWhere(+ (d) => d.machineId == 'remote',+ );+ expect(remote.machineName, 'remote computer');+ await controller.update(remote.key, {'brightness': 35});+ expect(controller.device(remote.key)!.status.settings!.brightness, 35);+ expect(controller.device(local.key)!.status.settings!.brightness, 80);+ expect(controller.saving(remote.key), isFalse);+ expect(+ connections['m']!.requests.where(+ (r) => r.$1 == 'harness_device_settings',+ ),+ isEmpty,+ );+ expect(connections['remote']!.requests.last.$2, {+ 'id': 'same-usb-id',+ 'patch': {'brightness': 35},+ });+ app.machineStates['remote']!+ ..nodeOnline = false+ ..connectionStatus = ConnectionStatus.disconnected;+ app.notifyListeners();+ expect(controller.device(remote.key)!.canEdit, isFalse);+ expect(controller.device(remote.key)!.connectionLabel, 'Computer offline');+ expect(controller.device(remote.key)!.status.settings!.brightness, 35);+ expect(+ await app.setHostDeviceSettings('remote', 'same-usb-id', {+ 'brightness': 90,+ }),+ isFalse,+ );+ expect(+ await app.setHostDeviceSettings('shared', 'same-usb-id', {+ 'brightness': 90,+ }),+ isFalse,+ );+ app.machineStates['remote']!+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ app.notifyListeners();+ expect(+ controller.device(remote.key)!.canEdit,+ isFalse,+ reason: 'Reconnection requires fresh device status',+ );+ await app.refreshDevices();+ expect(controller.device(remote.key)!.canEdit, isTrue);+ await controller.settled;+ final restored = DevicesController(+ hosts: DeviceHosts(),+ accountId: 'a',+ storage: storage,+ sendHostSettings: (_, _, _) async => false,+ );+ await restored.load();+ expect(restored.devices, hasLength(2));+ expect(restored.devices.every((d) => !d.canEdit), isTrue);+ expect(restored.device(remote.key)!.machineName, 'remote computer');+ restored.dispose();+ });++ test('late replies cannot cross an account change; old remote daemons never fall back to a local cable', () async {+ final connection = _DeviceConnection('m');+ final app = createApp(+ connected: true,+ connectionForTest: (_) => connection,+ );+ addTearDown(app.dispose);+ app.currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ );+ app.experimentalFeatures.bind('a', transport: AccountSettings('a'));+ await app.experimentalFeatures.refresh();+ await app.experimentalFeatures.set(ExperimentalFeature.devicesTab, true);+ connection.unsupported = true;+ await app.refreshDevices();+ expect(app.deviceHosts.host('m')!.available, isFalse);+ expect(app.deviceHosts.host('m')!.error, contains('Update Harness'));+ expect(+ await app.setHostDeviceSettings('m', 'same-usb-id', {'muted': false}),+ isFalse,+ );+ connection.unsupported = false;+ connection.held = Completer();+ final read = app.refreshDevices();+ await Future<void>.delayed(Duration.zero);+ app.currentUser = const CurrentUserProfile(+ id: 'b',+ email: '[email protected]',+ );+ connection.held!.complete(connection.snapshot);+ await read;+ expect(app.deviceHosts.hosts, isEmpty);+ });++ test('newer device reports beat stale replies, and firmware updates cancel pending edits', () async {+ final hosts = DeviceHosts();+ hosts.reconcile([const DeviceHost(id: 'm', name: 'Mac', online: true)]);+ DialStatus snapshot(DialStatus device) =>+ DialStatus(attached: true, devices: [device]);+ hosts.receive(+ 'm',+ snapshot(deviceStatus('usb', brightness: 70)),+ revision: 2,+ );+ final controller = DevicesController(+ hosts: hosts,+ accountId: 'a',+ sendHostSettings: (_, _, _) async => true,+ );+ await controller.load();+ final key = controller.devices.single.key;+ hosts.receive(+ 'm',+ snapshot(deviceStatus('usb', brightness: 20)),+ revision: 1,+ );+ expect(controller.device(key)!.status.settings!.brightness, 70);+ await controller.update(key, {'muted': false});+ hosts.receive(+ 'm',+ snapshot(deviceStatus('usb', updating: 'new firmware')),+ revision: 3,+ );+ expect(controller.saving(key), isFalse);+ expect(controller.deviceError(key), contains('updating'));+ hosts.receive(+ 'm',+ snapshot(const DialStatus(id: 'usb', attached: false)),+ revision: 4,+ );+ expect(controller.device(key)!.status.settings, isNotNull);+ hosts.receive(+ 'm',+ snapshot(const DialStatus(id: 'usb', attached: true)),+ revision: 5,+ );+ expect(+ controller.device(key)!.canEdit,+ isFalse,+ reason: 'An incomplete reconnect is not fresh settings',+ );+ controller.dispose();+ hosts.dispose();+ });+}diff --git a/desktop/test/devices_screen_test.dart b/desktop/test/devices_screen_test.dartnew file mode 100644index 000000000..97efd0e9f--- /dev/null+++ b/desktop/test/devices_screen_test.dart@@ -0,0 +1,287 @@+import 'dart:io';+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/devices/device_settings.dart';+import 'package:harness/devices/devices_controller.dart';+import 'package:harness/devices/devices_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/dial_status.dart';++import 'devices_controller_test.dart' show deviceStatus, report;+import 'support/real_fonts.dart';+import 'swarm_state_test.dart' show MemoryStore;++void main() {+ setUpAll(() async {+ await loadRealFonts();+ if (Platform.isMacOS) {+ final bytes = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(bytes))).load();+ }+ }+ final iconBytes = await rootBundle.load(+ 'packages/lucide_icons_flutter/assets/lucide.ttf',+ );+ await (FontLoader(+ 'packages/lucide_icons_flutter/Lucide400',+ )..addFont(Future.value(iconBytes))).load();+ });++ Future<void> pump(+ WidgetTester tester,+ DevicesController controller, {+ Brightness brightness = Brightness.light,+ Size size = const Size(1280, 940),+ double scale = 1,+ GlobalKey? capture,+ Future<bool> Function(Uri)? shop,+ }) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = size;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ grid.AppTheme.brightness.value = brightness;+ await tester.pumpWidget(+ RepaintBoundary(+ key: capture,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: grid.BrightnessScope(child: child!),+ ),+ home: Scaffold(+ body: DevicesScreen(controller: controller, openShop: shop),+ ),+ ),+ ),+ );+ await tester.runAsync(() async {+ final context = tester.element(find.byType(DevicesScreen));+ await Future.wait([+ for (final image in ['front', 'side', 'desk'])+ precacheImage(AssetImage('assets/devices/harness-$image.webp'), context),+ ]);+ });+ await tester.pumpAndSettle();+ }++ Future<void> capture(WidgetTester tester, GlobalKey key, String name) async {+ final output = Platform.environment['HARNESS_DEVICES_CAPTURE_DIR'];+ if (output == null) return;+ final render =+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ await tester.runAsync(() async {+ final image = await render.toImage(pixelRatio: 1);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(output).create(recursive: true);+ await File('$output/$name.png').writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ Future<DevicesController> fleet(DialState dial) async {+ final controller = DevicesController(+ dial: dial,+ accountId: 'review',+ storage: MemoryStore(),+ sendSettings: (_, _) async => true,+ );+ await controller.load();+ report(dial, [+ for (var i = 0; i < 5; i++) deviceStatus('$i', attached: i != 4),+ ]);+ const names = [+ 'Studio',+ 'Home office',+ 'Design desk',+ 'Workshop',+ 'Travel',+ ];+ for (var i = 0; i < 5; i++) {+ controller.rename(+ controller.devices[i].key,+ names[i],+ i < 2 ? HarnessDeviceModel.harness : HarnessDeviceModel.pro,+ );+ }+ return controller;+ }++ for (final brightness in Brightness.values) {+ for (final empty in [false, true]) {+ testWidgets(+ '${brightness.name} ${empty ? 'empty' : 'five-device'} product view',+ (tester) async {+ final dial = DialState();+ final controller = empty+ ? DevicesController(+ dial: dial,+ accountId: 'review',+ sendSettings: (_, _) async => true,+ )+ : await fleet(dial);+ final key = GlobalKey();+ await pump(tester, controller, brightness: brightness, capture: key);+ expect(tester.takeException(), isNull);+ expect(find.text('Shop'), findsOneWidget);+ if (!empty) {+ expect(find.text('Harness Pro'), findsNWidgets(3));+ expect(find.text('Faces'), findsOneWidget);+ }+ await capture(+ tester,+ key,+ '${brightness.name}-${empty ? 'empty' : 'devices'}',+ );+ await tester.pumpWidget(const SizedBox());+ controller.dispose();+ dial.dispose();+ },+ );+ }+ }++ testWidgets('narrow layouts and 200 percent text remain scrollable', (+ tester,+ ) async {+ final dial = DialState();+ final controller = await fleet(dial);+ final key = GlobalKey();+ await pump(+ tester,+ controller,+ size: const Size(620, 800),+ scale: 2,+ capture: key,+ );+ expect(tester.takeException(), isNull);+ final settings = find.byType(DeviceSettingsPanel);+ await tester.ensureVisible(settings);+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ await capture(tester, key, 'narrow-enlarged');+ await tester.pumpWidget(const SizedBox());+ controller.dispose();+ dial.dispose();+ });++ testWidgets(+ 'selected device owns changes through reorder and disconnect; Faces is a single choice',+ (tester) async {+ final dial = DialState();+ final sent = <(String, Map<String, Object?>)>[];+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ sendSettings: (id, patch) async {+ sent.add((id, patch));+ return true;+ },+ );+ await controller.load();+ report(dial, [deviceStatus('a'), deviceStatus('b')]);+ await pump(tester, controller);+ final key = controller.devices.last.key;+ await tester.tap(find.byKey(ValueKey('device-card-$key')));+ await tester.pumpAndSettle();+ report(dial, [deviceStatus('b'), deviceStatus('a')]);+ await tester.pumpAndSettle();+ final sound = find.byKey(ValueKey('devices-sound-$key'));+ await tester.ensureVisible(sound);+ await tester.tap(sound);+ await tester.pump();+ expect(sent, hasLength(1));+ expect(sent.single.$1, 'b');+ expect(sent.single.$2, {'muted': false});+ expect(tester.widget<Switch>(sound).value, isFalse);+ expect(tester.widget<Switch>(sound).onChanged, isNull);+ report(dial, [deviceStatus('b', muted: false)]);+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(sound).value, isTrue);+ report(dial, []);+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(sound).onChanged, isNull);+ final faces = find.byKey(const Key('devices-faces'));+ await tester.ensureVisible(faces);+ await tester.tap(faces);+ await tester.pumpAndSettle();+ expect(deviceFaces, hasLength(1));+ expect(find.textContaining('New faces will appear'), findsOneWidget);+ await tester.tap(find.text('Done'));+ await tester.pumpAndSettle();+ expect(+ sent,+ hasLength(1),+ reason: 'Inspecting the current face never writes',+ );+ await tester.pumpWidget(const SizedBox());+ controller.dispose();+ dial.dispose();+ },+ );++ testWidgets(+ 'USB setup adds the actual device, saves Pro model, and Shop opens the product page',+ (tester) async {+ final dial = DialState();+ final storage = MemoryStore();+ final opened = <Uri>[];+ final controller = DevicesController(+ dial: dial,+ accountId: 'a',+ storage: storage,+ sendSettings: (_, _) async => true,+ );+ await pump(+ tester,+ controller,+ shop: (url) async {+ opened.add(url);+ return true;+ },+ );+ await tester.tap(find.text('Shop'));+ await tester.pumpAndSettle();+ expect(opened, [harnessDeviceShopUrl]);+ await tester.tap(find.byKey(const Key('devices-add')));+ await tester.pumpAndSettle();+ expect(find.text('Waiting for a USB connection…'), findsOneWidget);+ expect(+ tester+ .widget<FilledButton>(+ find.widgetWithText(FilledButton, 'Finish setup'),+ )+ .onPressed,+ isNull,+ );+ report(dial, [deviceStatus('new')]);+ await tester.pumpAndSettle();+ await tester.tap(find.text('Harness').last);+ await tester.pumpAndSettle();+ await tester.tap(find.text('Harness Pro').last);+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'Office Pro');+ await tester.ensureVisible(find.text('Finish setup'));+ await tester.tap(find.text('Finish setup'));+ await tester.pumpAndSettle();+ expect(controller.devices.single.name, 'Office Pro');+ expect(controller.devices.single.model, HarnessDeviceModel.pro);+ await controller.settled;+ expect(storage.values.values.single, contains('Office Pro'));+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ controller.dispose();+ dial.dispose();+ },+ );+}diff --git a/desktop/test/devices_tab_test.dart b/desktop/test/devices_tab_test.dartnew file mode 100644index 000000000..f0611ab10--- /dev/null+++ b/desktop/test/devices_tab_test.dart@@ -0,0 +1,146 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/settings/experimental_features.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/swarm.dart';++import 'support/experimental_settings.dart';+import 'swarm_screen_test.dart' show mount;+import 'swarm_state_test.dart' show MemoryStore, createApp;++void main() {+ for (final composerInBox in [false, true]) {+ testWidgets(+ 'Devices stays hidden until enabled and owns focus (composerInBox=$composerInBox)',+ (tester) async {+ newHarnessOpensInBox = composerInBox;+ addTearDown(() => newHarnessOpensInBox = false);+ final storage = MemoryStore();+ final app = createApp(store: storage);+ app.experimentalFeatures.bind(+ 'u1',+ transport: MemoryExperimentalTransport(storage),+ );+ await app.experimentalFeatures.refresh();+ await mount(tester, app);+ final button = find.byKey(const ValueKey('swarm-devices-button'));+ expect(button, findsNothing);+ app.openDevices();+ expect(app.activeSwarm.isDevices, isFalse);+ await app.experimentalFeatures.set(+ ExperimentalFeature.devicesTab,+ true,+ );+ await tester.pumpAndSettle();+ expect(button, findsOneWidget);+ expect(+ tester.getCenter(button).dx,+ greaterThan(+ tester+ .getCenter(find.byKey(const ValueKey('swarm-search-button')))+ .dx,+ ),+ );+ expect(+ tester.getCenter(button).dx,+ lessThan(+ tester+ .getCenter(find.byKey(const ValueKey('swarm-store-button')))+ .dx,+ ),+ );+ await tester.tap(button);+ await tester.pumpAndSettle();+ expect(app.activeSwarm.isDevices, isTrue);+ app.openDevices();+ expect(app.swarms.where((s) => s.isDevices), hasLength(1));+ expect(find.text('Add your first device'), findsOneWidget);+ expect(+ tester+ .widget<Offstage>(find.byKey(const ValueKey('workspace-canvas')))+ .offstage,+ isFalse,+ );+ final canvasFocus = find+ .descendant(+ of: find.byKey(const ValueKey('workspace-canvas')),+ matching: find.byType(ExcludeFocus, skipOffstage: false),+ skipOffstage: false,+ )+ .first;+ expect(tester.widget<ExcludeFocus>(canvasFocus).excluding, isFalse);+ expect(app.activeSwarm.panes.single.isDevices, isTrue);+ await app.experimentalFeatures.set(+ ExperimentalFeature.devicesTab,+ false,+ );+ await tester.pumpAndSettle();+ expect(button, findsNothing);+ expect(app.swarms.any((s) => s.isDevices), isFalse);+ expect(find.text('Add your first device'), findsNothing);+ await app.experimentalFeatures.set(+ ExperimentalFeature.devicesTab,+ true,+ );+ app.openDevices();+ await tester.pumpAndSettle();+ app.currentUser = const CurrentUserProfile(+ id: 'u2',+ email: '[email protected]',+ );+ await tester.pumpAndSettle();+ expect(button, findsNothing);+ expect(app.swarms.any((s) => s.isDevices), isFalse);+ expect(find.text('Add your first device'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+ }++ test(+ 'a saved Devices tab cannot appear when the experiment is off',+ () async {+ final storage = MemoryStore();+ await PaneLayoutStore(storage: storage).saveSwarms([+ Swarm(id: 'devices', name: 'Devices', kind: 'devices'),+ Swarm(id: 'work', name: 'Work'),+ ], 'devices');+ final app = createApp(store: storage);+ await app.restorePaneLayoutForTest();+ expect(app.swarms.any((s) => s.isDevices), isFalse);+ app.dispose();+ },+ );++ test(+ 'older servers keep existing experiments working with Devices unavailable',+ () async {+ final store = ExperimentalFeaturesStore(pollInterval: Duration.zero);+ store.bind('u1', transport: _OldServer());+ await store.refresh();+ expect(store.loaded, isTrue);+ expect(store.enabled(ExperimentalFeature.shareButton), isTrue);+ expect(store.enabled(ExperimentalFeature.devicesTab), isFalse);+ expect(store.isAvailable(ExperimentalFeature.devicesTab), isFalse);+ store.dispose();+ },+ );+}++class _OldServer implements ExperimentalSettingsTransport {+ @override+ Future<Map<String, dynamic>> read() async => {+ 'accountId': 'u1',+ 'revision': 1,+ 'features': {'focus_bar_creature': false, 'share_button': true},+ };+ @override+ Future<Map<String, dynamic>> write(+ String accountId,+ ExperimentalFeature feature,+ bool enabled,+ ) => read();+}diff --git a/desktop/test/workspace_event_isolation_test.dart b/desktop/test/workspace_event_isolation_test.dartindex 6a69e6368..bea8e3d61 100644--- a/desktop/test/workspace_event_isolation_test.dart+++ b/desktop/test/workspace_event_isolation_test.dart@@ -191,6 +191,7 @@ void main() {final app = createApp();addTearDown(app.dispose);var workspaceChanges = 0;+ app.machineStates['m']!.localOnly = true;var deviceChanges = 0;app.addListener(() => workspaceChanges++);app.dial.addListener(() => deviceChanges++);diff --git a/desktop/tool/devices_preview.dart b/desktop/tool/devices_preview.dartnew file mode 100644index 000000000..7e45e6d27--- /dev/null+++ b/desktop/tool/devices_preview.dart@@ -0,0 +1,445 @@+// Interactive review combining the Devices work from site-apple and ab-mac-3.+// Build with scripts/build-devices-review.sh. All hardware and storage are fake.+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/devices/devices_controller.dart';+import 'package:harness/devices/devices_harness_controller.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/settings/experimental_features.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/theme/color_palette.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/dial_status.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/pane_arrangement.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:window_manager/window_manager.dart';++Future<void> main() async {+ if (!kDebugMode ||+ !kUnderTest ||+ !const bool.fromEnvironment('DEVICES_REVIEW')) {+ throw StateError(+ 'Preview requires HARNESS_TEST and DEVICES_REVIEW in a debug build.',+ );+ }+ WidgetsFlutterBinding.ensureInitialized();+ grid.AppTheme.palette.value = HarnessPalette.paper;+ grid.AppTheme.brightness.value = Brightness.light;+ await windowManager.ensureInitialized();+ await const MethodChannel(+ 'harness/swarm_tabs',+ ).invokeMethod('configure', {'palette': HarnessPalette.paper.nativeColors});+ await windowManager.setSize(const Size(1360, 1040));+ await windowManager.setTitle('Devices Review — sample hardware');+ final app = DevicesReviewApp();+ await app.prepare();+ runApp(_Preview(app: app));+ await windowManager.show();+ await windowManager.focus();+}++class DevicesReviewStorage implements LocalKeyValueStore {+ final values = <String, String>{};+ @override+ Future<String?> read(String key) async => values[key];+ @override+ Future<void> write(String key, String value) async {+ values[key] = value;+ }++ @override+ Future<void> delete(String key) async {+ values.remove(key);+ }+}++class _Experiments implements ExperimentalSettingsTransport {+ final features = {+ for (final feature in ExperimentalFeature.values)+ feature.id: feature == ExperimentalFeature.devicesTab,+ };+ int revision = 0;+ @override+ Future<Map<String, dynamic>> read() async => {+ 'accountId': 'preview',+ 'revision': revision,+ 'features': Map.of(features),+ };+ @override+ Future<Map<String, dynamic>> write(+ String account,+ ExperimentalFeature feature,+ bool enabled,+ ) async {+ features[feature.id] = enabled;+ revision++;+ return read();+ }+}++/// Shared by the standalone review and native integration test. Never talks to+/// the real daemon or writes the signed-in person's preferences.+class DevicesReviewApp extends AppNotifier {+ DevicesReviewApp() : this._(DevicesReviewStorage());+ DevicesReviewApp._(this.storage)+ : super(+ config: const AppConfig(+ apiBaseUrl: 'http://127.0.0.1:1',+ localCliBaseUrl: 'http://127.0.0.1:1',+ ),+ authSession: AuthSession(),+ paneLayoutStore: PaneLayoutStore(storage: storage),+ experimentalSettingsTransport: _Experiments(),+ ) {+ if (!kUnderTest) throw StateError('Devices review requires test mode.');+ status = AppStatus.authenticated;+ hasNavigationRail = false;+ currentUser = const CurrentUserProfile(+ id: 'preview',+ email: '[email protected]',+ );+ const hosts = [+ Machine(+ machineId: 'studio-mac',+ authMode: MachineAuthMode.remote,+ name: 'Studio Mac',+ ),+ Machine(+ machineId: 'office-mac',+ authMode: MachineAuthMode.remote,+ name: 'Office Mac',+ ),+ Machine(+ machineId: 'workshop-pc',+ authMode: MachineAuthMode.remote,+ name: 'Workshop PC',+ ),+ ];+ machines = hosts;+ for (final host in hosts) {+ machineStates[host.machineId] = MachineState(host)+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..localOnly = host.machineId == 'studio-mac'+ ..nodeOnline = host.machineId != 'workshop-pc'+ ..connectionStatus = host.machineId == 'workshop-pc'+ ? ConnectionStatus.disconnected+ : ConnectionStatus.connected;+ }+ notifyListeners();+ }++ final DevicesReviewStorage storage;+ final _samples = <DialStatus>[];+ final _sampleHosts = <String>[];+ final writes = <(String, String, Map<String, Object?>)>[];+ bool _ended = false;++ Future<void> prepare({bool empty = false}) async {+ await experimentalFeatures.refresh();+ if (!empty) {+ for (var i = 0; i < 5; i++) {+ connectSample(+ machineId: i < 2+ ? 'studio-mac'+ : i < 4+ ? 'office-mac'+ : 'workshop-pc',+ );+ }+ const names = [+ 'Studio',+ 'Home office',+ 'Design desk',+ 'Workshop',+ 'Travel',+ ];+ await storage.write(+ 'harness_devices_v1.preview',+ jsonEncode([+ for (var i = 0; i < _samples.length; i++)+ HarnessDevice(+ key:+ '${_sampleHosts[i]}/${DevicesController.identity(_samples[i])}',+ name: names[i],+ model: i < 2+ ? HarnessDeviceModel.harness+ : HarnessDeviceModel.pro,+ status: _samples[i],+ machineId: _sampleHosts[i],+ machineName: machineStates[_sampleHosts[i]]!.machine.displayName,+ ).toJson(),+ ]),+ );+ }+ openDevices();+ machineStates['studio-mac']!.agents = [+ const Agent(+ id: 'review-devices',+ name: 'Devices',+ engine: 'codex',+ dsh: devicesHarnessId,+ terminalAvailable: true,+ ),+ ];+ await showDevicesTerminal('studio-mac', 'review-devices');+ }++ @override+ Future<void> showDevicesTerminal(String machineId, String agentId) async {+ final tab = swarms.where((tab) => tab.isDevices).firstOrNull;+ if (tab == null || tab.panes.any((pane) => pane.agentId == agentId)) return;+ final session =+ TerminalSession(+ machineId: machineId,+ agentId: agentId,+ agentName: 'Devices',+ engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'devices-review';+ session.terminal.write(+ 'Devices\r\n\r\nYour Harness hardware, across your computers.\r\n\r\nTry the controls in the dashboard.\r\n\r\nThis review uses sample hardware and a\r\nsample conversation. No agent is running.\r\n',+ );+ tab.panes.add(+ TerminalPane(id: 900001, machineId: machineId, agentId: agentId)+ ..session = session,+ );+ tab.paneSizes['2:manual'] = PaneArrangement.viewerBesideTerminal;+ notifyListeners();+ }++ void connectSample({bool attached = true, String machineId = 'studio-mac'}) {+ final i = _samples.length;+ _sampleHosts.add(machineId);+ _samples.add(+ DialStatus.fromJson({+ 'id': 'preview-$i',+ 'mac': '02:00:00:00:00:${i.toRadixString(16).padLeft(2, '0')}',+ 'attached': attached,+ 'fw': '0.0.101',+ 'settings': {+ 'brightness': 80,+ 'character': 2,+ 'face': 466,+ 'round': true,+ 'muted': true,+ 'quiet': false,+ 'straightTitle': true,+ 'focusFace': false,+ 'scrollReversed': false,+ 'voiceLang': 'en',+ },+ }),+ );+ _publish();+ }++ DialStatus _copy(+ DialStatus device, {+ bool? attached,+ Map<String, Object?>? patch,+ }) => DialStatus(+ id: device.id,+ mac: device.mac,+ fw: device.fw,+ attached: attached ?? device.attached,+ settings: patch == null+ ? device.settings+ : DeviceSettings.fromJson({...device.settings!.toJson(), ...patch}),+ );++ void setConnected(bool connected) {+ for (final host in machineStates.values) {+ host.nodeOnline = connected;+ host.connectionStatus = connected+ ? ConnectionStatus.connected+ : ConnectionStatus.disconnected;+ }+ for (var i = 0; i < _samples.length; i++) {+ _samples[i] = _copy(_samples[i], attached: connected);+ }+ _publish();+ }++ void _publish() {+ notifyListeners();+ for (final host in machineStates.values) {+ final devices = [+ for (var i = 0; i < _samples.length; i++)+ if (_sampleHosts[i] == host.machine.machineId) _samples[i],+ ];+ final snapshot = DialStatus(+ attached: devices.any((d) => d.attached),+ devices: devices,+ );+ deviceHosts.receive(host.machine.machineId, snapshot);+ if (host.isLocalMachine) dial.apply(snapshot);+ }+ }++ @override+ Future<void> refreshDevices() async {+ await Future<void>.delayed(Duration.zero);+ if (!_ended) _publish();+ }++ @override+ Future<bool> setHostDeviceSettings(+ String machineId,+ String id,+ Map<String, Object?> patch,+ ) async {+ writes.add((machineId, id, Map.of(patch)));+ await Future<void>.delayed(const Duration(milliseconds: 350));+ if (_ended) return false;+ final i = _samples.indexWhere((d) => d.id == id && d.attached);+ if (i < 0 ||+ _sampleHosts[i] != machineId ||+ deviceHosts.host(machineId)?.online != true) {+ return false;+ }+ _samples[i] = _copy(_samples[i], patch: patch);+ _publish();+ return true;+ }++ @override+ void dispose() {+ _ended = true;+ super.dispose();+ }+}++class _Preview extends StatefulWidget {+ const _Preview({required this.app});+ final DevicesReviewApp app;+ @override+ State<_Preview> createState() => _PreviewState();+}++class _PreviewState extends State<_Preview> {+ late DevicesReviewApp app = widget.app;+ bool dark = false, empty = false, switching = false;++ Future<void> _toggleSamples() async {+ if (switching) return;+ setState(() => switching = true);+ // Unmount before replacing the app: disposal clears its native channel.+ await WidgetsBinding.instance.endOfFrame;+ if (!mounted) return;+ app.dispose();+ final next = DevicesReviewApp();+ await next.prepare(empty: !empty);+ if (!mounted) {+ next.dispose();+ return;+ }+ setState(() {+ app = next;+ empty = !empty;+ switching = false;+ });+ }++ @override+ void dispose() {+ app.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(+ brightness: dark ? Brightness.dark : Brightness.light,+ ),+ builder: (context, child) => grid.BrightnessScope(child: child!),+ home: Column(+ children: [+ Material(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),+ child: Wrap(+ spacing: 12,+ runSpacing: 6,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ const Text('Devices review · Sample hardware'),+ TextButton(+ onPressed: () => setState(() {+ dark = !dark;+ grid.AppTheme.palette.value = dark+ ? HarnessPalette.graphite+ : HarnessPalette.paper;+ grid.AppTheme.brightness.value = dark+ ? Brightness.dark+ : Brightness.light;+ }),+ child: Text(dark ? 'Light appearance' : 'Dark appearance'),+ ),+ TextButton(+ onPressed: switching ? null : _toggleSamples,+ child: Text(empty ? 'Show five devices' : 'Show empty state'),+ ),+ TextButton(+ onPressed: switching ? null : () => app.connectSample(),+ child: const Text('Connect sample device'),+ ),+ ListenableBuilder(+ listenable: app.dial,+ builder: (context, _) => TextButton(+ onPressed: switching+ ? null+ : () => app.setConnected(+ !app.dial.devices.any((d) => d.attached),+ ),+ child: Text(+ app.dial.devices.any((d) => d.attached)+ ? 'Disconnect devices'+ : 'Reconnect devices',+ ),+ ),+ ),+ TextButton(+ onPressed: switching+ ? null+ : () async {+ await app.experimentalFeatures.set(+ ExperimentalFeature.devicesTab,+ !app.devicesEnabled,+ );+ if (app.devicesEnabled) app.openDevices();+ },+ child: const Text('Toggle experiment'),+ ),+ ],+ ),+ ),+ ),+ Expanded(+ child: switching+ ? const SizedBox.expand()+ : SwarmScreen(+ key: ObjectKey(app),+ notifier: app,+ nativeTabs: true,+ projectStore: SwarmProjectStore(storage: app.storage),+ ),+ ),+ ],+ ),+ );+}diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex bb6880f93..0fd1b6305 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -1173,6 +1173,9 @@ private extension SwarmTabStrip {"Search and Store stay adjacent after the tabs at width \(width)")try checkTitlebar(!subviews.contains { $0.accessibilityLabel() == "Notifications" },"Notifications live in the macOS menu bar, with no duplicate titlebar bell")+ try checkTitlebar(devicesButton.isHidden && !devicesButton.isEnabled &&+ accessibilityChildren()?.contains(where: { $0 as? NSView === devicesButton }) == false,+ "Devices stays hidden and outside accessibility navigation until opted in")try checkTitlebar(searchButton.toolTip == state["searchTooltip"] as? String &&searchButton.accessibilityHelp() == searchButton.toolTip &&storeButton.toolTip == state["storeTooltip"] as? String &&@@ -1183,14 +1186,38 @@ private extension SwarmTabStrip {storeButton.performClick(nil)try checkTitlebar(calls == ["sessions", "store"],"Top actions open the existing search and Store surfaces")+ state["devicesVisible"] = true+ for width in [CGFloat(360), CGFloat(640), CGFloat(1280)] {+ setFrameSize(NSSize(width: width, height: 40))+ update(state)+ try checkTitlebar(!devicesButton.isHidden && devicesButton.isEnabled &&+ searchButton.frame.maxX < devicesButton.frame.minX &&+ devicesButton.frame.maxX < storeButton.frame.minX &&+ newButton.frame.maxX < searchButton.frame.minX &&+ devicesButton.font == storeButton.font &&+ accessibilityChildren()?.contains(where: { $0 as? NSView === devicesButton }) == true,+ "Opted-in navigation reads Search, Devices, Store at width \(width)")+ }+ devicesButton.performClick(nil)+ try checkTitlebar(calls == ["sessions", "store", "devices"],+ "Devices opens its workspace through the native action")state["enabled"] = falseupdate(state)searchButton.performClick(nil)storeButton.performClick(nil)- try checkTitlebar(!searchButton.isEnabled && !storeButton.isEnabled && calls.count == 2,+ devicesButton.performClick(nil)+ try checkTitlebar(!searchButton.isEnabled && !storeButton.isEnabled &&+ !devicesButton.isEnabled && calls.count == 3,"A modal prevents toolbar actions")+ state["enabled"] = true+ state["devicesVisible"] = false+ update(state)+ devicesButton.performClick(nil)+ try checkTitlebar(devicesButton.isHidden && !devicesButton.isEnabled && calls.count == 3,+ "Turning the experiment off removes and disables the native entry")update([:])- try checkTitlebar(!searchButton.isEnabled && !storeButton.isEnabled,+ try checkTitlebar(!searchButton.isEnabled && !storeButton.isEnabled &&+ devicesButton.isHidden && !devicesButton.isEnabled,"Teardown disables the toolbar")}@@ -1624,7 +1651,7 @@ private extension SwarmTabStrip {newButton.frame.maxX < searchButton.frame.minX, "Tabs precede the search and Store controls")try checkTitlebar(tabs[0].frame.width < 136 && tabs[0].displayLabel == "code","Overflow tabs keep readable names without persistent number prefixes")- try checkTitlebar(subviews.count == 4 && statusBar.subviews.count == 8 && machineResourcesLabel.isHidden && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && harnessMonitorButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,+ try checkTitlebar(subviews.filter { !$0.isHidden }.count == 4 && devicesButton.isHidden && statusBar.subviews.count == 8 && machineResourcesLabel.isHidden && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && harnessMonitorButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,"Navigation lives in the titlebar and focused context lives in the footer")let controls = [newButton]for control in controls {diff --git a/docs/research/2026-10-01-devices/dark-devices-dsh.png b/docs/research/2026-10-01-devices/dark-devices-dsh.pngnew file mode 100644index 000000000..f74cea238Binary files /dev/null and b/docs/research/2026-10-01-devices/dark-devices-dsh.png differdiff --git a/docs/research/2026-10-01-devices/dark-devices.png b/docs/research/2026-10-01-devices/dark-devices.pngnew file mode 100644index 000000000..99894b0deBinary files /dev/null and b/docs/research/2026-10-01-devices/dark-devices.png differdiff --git a/docs/research/2026-10-01-devices/light-devices-dsh.png b/docs/research/2026-10-01-devices/light-devices-dsh.pngnew file mode 100644index 000000000..4fb23fe9dBinary files /dev/null and b/docs/research/2026-10-01-devices/light-devices-dsh.png differdiff --git a/docs/research/2026-10-01-devices/light-devices.png b/docs/research/2026-10-01-devices/light-devices.pngnew file mode 100644index 000000000..65ff3a0e2Binary files /dev/null and b/docs/research/2026-10-01-devices/light-devices.png differdiff --git a/docs/research/2026-10-01-devices/light-empty.png b/docs/research/2026-10-01-devices/light-empty.pngnew file mode 100644index 000000000..74fea71d7Binary files /dev/null and b/docs/research/2026-10-01-devices/light-empty.png differdiff --git a/docs/research/2026-10-01-devices/narrow-enlarged.png b/docs/research/2026-10-01-devices/narrow-enlarged.pngnew file mode 100644index 000000000..281d1a0b0Binary files /dev/null and b/docs/research/2026-10-01-devices/narrow-enlarged.png differdiff --git a/docs/research/2026-10-01-devices/offline-devices-dsh.png b/docs/research/2026-10-01-devices/offline-devices-dsh.pngnew file mode 100644index 000000000..68fdd345fBinary files /dev/null and b/docs/research/2026-10-01-devices/offline-devices-dsh.png differdiff --git a/store/agents/devices/AGENTS.md b/store/agents/devices/AGENTS.mdnew file mode 100644index 000000000..ae0f9b657--- /dev/null+++ b/store/agents/devices/AGENTS.md@@ -0,0 +1,45 @@+# Devices++These instructions apply in a materialized Devices workspace with `devices.json`.+Help the person manage their physical Harness and Harness Pro devices. Your native+Devices dashboard sits beside this ordinary agent terminal. It is available from+Settings → Experimental → Devices; the package is bundled and unlisted.++Read live state with `harness hardware list --json`. Each result names the host+computer and its USB devices. Use the exact machineId and device id from that+result: the same USB id can exist on different computers. When a name is+ambiguous, ask which computer or device before changing it. Offline or unlinked+computers cannot accept changes; never queue an edit for later or interpret an+unavailable computer as having no devices. Linking belongs in Machines.++For a requested change, use:++```sh+harness hardware set --machine <machineId> --device <id> --patch '{"brightness":50}' --json+```++Only send the fields the person requested. Supported settings from production+firmware are brightness (integer 0–100), muted (true turns sound off), quiet+(notifications), scrollReversed, voiceLang (language code), straightTitle,+focusFace and followCompanion. The initial face is Focus, character 2. Do not+offer other faces yet. Do not confuse `face` (display dimensions) with a face+choice, and never infer Harness versus Harness Pro from display dimensions.++`confirmed: true` means the device reported the requested values. An accepted+write without confirmation is pending or refused: state that plainly. Never+claim a setting changed from an optimistic write or a cached observation. The+daemon owns USB and authenticated encrypted routing; do not open serial ports,+read credentials, start another device process, or replace this dashboard.++Adding a device means connecting it by USB to a computer running Harness on the+same account, then choosing Add device in the dashboard to name it and select+its model. Names and model labels are saved by the dashboard on this computer.+There is no Bluetooth or Wi-Fi pairing and no battery reading. For purchasing,+point to the dashboard's Shop button or https://www.autonomous.ai/harness-device.+Do not invent model specifications or prices. Do not flash firmware, reset a+device, or change accounts as part of ordinary settings work.++Use short, concrete replies: which device, on which computer, what changed.+A greeting needs a greeting and an offer to show or adjust devices; it does not+authorize edits. The person's existing request authorizes its settings change.+Keep optional user notes in `devices.json`; it is not the live device inventory.diff --git a/store/agents/devices/LICENSE b/store/agents/devices/LICENSEnew file mode 100644index 000000000..a499cd17e--- /dev/null+++ b/store/agents/devices/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Autonomous, Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/store/agents/devices/README.md b/store/agents/devices/README.mdnew file mode 100644index 000000000..d6fcf842f--- /dev/null+++ b/store/agents/devices/README.md@@ -0,0 +1,53 @@+# Devices++Manage physical Harness and Harness Pro devices across computers linked to your+account. The native dashboard opens beside an ordinary agent conversation, with+each USB device labeled by its host computer.++Devices is bundled with the Harness CLI, unlisted in the Store, and off by+default. With an updated backend, desktop app, and daemons, enable **Settings →+Experimental → Devices**, then click **Devices** beside Harness Store. An+installed, configured Codex, Claude Code, or OpenCode engine is needed for the+conversation. Engine account and usage requirements still apply.++Try asking:++> Show my Harness devices and the computers they are connected to.++The agent reads live inventory and reports the owning computers, available+devices, and unavailable hosts. A requested settings change targets one host+and one device and waits for the device to report the requested values. Offline+controls are disabled; changes are never queued for later.++The dashboard supports brightness, sound, reverse scrolling, voice language,+and the initial Focus face. Add device guides USB connection, naming, and model+selection; Shop opens the [Harness product page](https://www.autonomous.ai/harness-device).+Names and chosen model labels are saved locally per account. Firmware does not+identify the retail model, and the package adds no wireless pairing or battery+telemetry.++## Development and verification++From the repository root, after building the CLI:++```sh+node cli/dist/cli.js dsh check store/agents/devices+node cli/dist/cli.js hardware list --json+```++The first command validates the package without starting an agent. The second+requires a running, signed-in daemon and reads the actual account inventory.+The agent uses `harness hardware list/set` through the authenticated daemon;+`harness devices` continues to manage account device keys.++Desktop tests and the separate Devices Review app use sample hardware and a+sample conversation. They do not constitute a live engine, USB, or cross-machine+acceptance test. The native viewer lives in `desktop/lib/devices/`; the package's+`devices.json` is for optional notes, not device discovery or live settings.++## Credit and stewardship++Created and maintained by Autonomous as part of OpenHarness. This package is+licensed under the [MIT License](LICENSE). Dashboard product photography comes+from Autonomous; source URLs are recorded in+[the desktop asset notes](../../../desktop/assets/devices/README.md).diff --git a/store/agents/devices/harness.json b/store/agents/devices/harness.jsonnew file mode 100644index 000000000..c2f2eed32--- /dev/null+++ b/store/agents/devices/harness.json@@ -0,0 +1,11 @@+{+ "spec": 1,+ "id": "autonomous/devices",+ "name": "Devices",+ "category": "Hardware",+ "author": "Autonomous",+ "description": "Manage your Harness devices across your computers, with a dashboard and a conversation.",+ "engine": "codex",+ "workspace": { "template": "template", "marker": "devices.json" },+ "agent": { "instructions": "AGENTS.md", "env": { "DSH_PERMISSION_MODE": "ask" } }+}diff --git a/store/agents/devices/store.json b/store/agents/devices/store.jsonnew file mode 100644index 000000000..bab5bf672--- /dev/null+++ b/store/agents/devices/store.json@@ -0,0 +1,6 @@+{+ "listed": false,+ "homepage": "https://www.autonomous.ai/harness-device",+ "license": "MIT",+ "tagline": "Your devices, across your computers"+}diff --git a/store/agents/devices/template/devices.json b/store/agents/devices/template/devices.jsonnew file mode 100644index 000000000..e8468fce9--- /dev/null+++ b/store/agents/devices/template/devices.json@@ -0,0 +1 @@+{"spec":1,"notes":{}}