Skip to content

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

Headless Harness OS: set up from a phone, and its update and Wi-Fi from the app

bubu-duduc3616e42d9eb
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 6d3083000..f92f6367e 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -762,7 +762,7 @@ export class BackendSocket {
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = rpcResultType(type)
// Before the E2EE wrap: an RPC reply is only readable here.
- if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
if (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
@@ -821,7 +821,7 @@ export class BackendSocket {
// actually asked for rather than as an opaque __e2e envelope.
// Terminal frames contain raw keystrokes, paste text and screen bytes after
// unwrap. Never pass them to the frame logger, even in diagnostic mode.
- if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const launchMeasured = productUsageLaunch(type, (frame.payload as { creationId?: unknown } | undefined)?.creationId,
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 7996fdf67..444098559 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -523,6 +523,9 @@ export const WINDOW_NAMES_REQUESTS = ['window_name'] as const
export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as const
/** Connected services for every local agent, and their MCP bridge, in the edge host (services/connectors.ts). */
export const CONNECTORS_REQUESTS = ['connectors'] as const
+/** A Harness OS computer managed from the owner's phone: whether it runs Harness OS, its update, and its Wi-Fi,
+ * in the edge host (services/osDevice.ts). */
+export const OS_DEVICE_REQUESTS = ['os_device'] as const
/**
* Models (services/models.ts).
*
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 6650af8a9..fab09776b 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -167,7 +167,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn
import { createCursorDiscovery } from './engines/cursorDiscovery.js'
import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'
import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
-import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
+import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -1293,7 +1293,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The requests each service that can run in its own process answers, as core/api.ts declares them.
const requestsOf: Record<string, readonly string[]> = {
search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS, connectors: CONNECTORS_REQUESTS,
- devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS, messages: MESSAGES_REQUESTS,
+ devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS, messages: MESSAGES_REQUESTS, osDevice: OS_DEVICE_REQUESTS,
...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),
}
// The experiments (core/api.ts `EXPERIMENTS`): each may act on the core through the hooks an experiment has.
@@ -1504,6 +1504,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)
// Connected services' MCP bridge and the Connectors screen (services/connectors.ts): here, or in the edge host.
if (!outOfProcess.has('connectors')) serviceHost.serve('connectors', inline!.startConnectors, coreApi, CONNECTORS_REQUESTS)
+ // A Harness OS computer managed from the owner's phone: its update and its Wi-Fi (services/osDevice.ts): here, or in the edge host.
+ if (!outOfProcess.has('osDevice')) serviceHost.serve('osDevice', inline!.startOsDevice, coreApi, OS_DEVICE_REQUESTS)
// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.
if (outOfProcess.has('recaps')) ports.recaps = recapsLink.port; else serviceHost.start('recaps', inline!.startRecaps, coreApi, RECAPS_FALLBACKS)
// Cleaning up after agents: the harnesses a closed harness started, and those idle half an hour (services/agentCleanup.ts).
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 900250bf1..955e33a1e 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -494,7 +494,7 @@ describe('ServiceSupervisor', () => {
const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)
expect(KNOWN_SERVICES).toEqual(hosted)
expect(new Set(hosted).size).toBe(hosted.length)
- expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages'])
+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages', 'osDevice'])
// Agent Messages has no process of its own: one cost every computer it was on 62 MiB at idle (2026-10-12).
expect(Object.keys(SERVICE_HOSTS)).not.toContain('messages')
})
@@ -549,7 +549,7 @@ describe('which services the core leaves to its master', () => {
expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })
// By service, not by process: a core from before the edge host routes the services it knows of it.
const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)
- expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
+ expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages,osDevice', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell,connectors,agentCleanup,messages,osDevice', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted, 42) }, known)]).toEqual(['workspaces', 'messages'])
expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1', [ENGINE_SUBMISSION_ENV]: '42:1', [ENGINE_NATIVE_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs, 42) }, known)]).toEqual(['search', 'workspaces'])
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 46e69d195..e76048648 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -390,8 +390,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// account's tabs, and runs no timer while it is off here or this computer is signed out. It had a process of its
// own as an experiment, 62 MiB resident at idle on every computer it was on, nearly all of it a second Node and
// the bundle rather than messaging: here it costs the edge host about 1 MiB on, and 0.4 MiB off
- // (e2e/footprint.e2e.ts, 2026-10-12).
- edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages'], heapLimitMiB: 384, rssLimitMiB: 768 },
+ // (e2e/footprint.e2e.ts, 2026-10-12). The Harness OS computer's management (services/osDevice.ts) holds one
+ // timestamp and runs its commands bounded, or detached when they must outlive this process.
+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell', 'connectors', 'agentCleanup', 'messages', 'osDevice'], heapLimitMiB: 384, rssLimitMiB: 768 },
// The orchestrator (services/orchestratorProcess.ts), an experiment: started only once it is on, for a
// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their
// Directors; the agents it runs are the core's.
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index 40c25143c..c59159919 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -30,6 +30,8 @@ const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_workt
'memory_snapshot', 'memory_about_put', 'memory_deliver',
// Cloud agents (services/cloud.ts): a cloud harness's conversation, the person's words for it, which are connected.
'cloud_transcript', 'cloud_send', 'cloud_agents',
+ // A Harness OS computer managed from the phone (services/osDevice.ts): a Wi-Fi join carries the network's password.
+ 'os_device',
// A sign-in a phone caught for a page a harness's program opened (core/terminals/browser.ts): it holds the code.
'browser_callback', ...ROUTE_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index fd02338b9..64c7e3799 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -41,6 +41,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['shell', async () => (await import('./services/shellProcess.js')).runShellService],
['handoff', async () => (await import('./services/handoffProcess.js')).runHandoffService],
['connectors', async () => (await import('./services/connectorsProcess.js')).runConnectorsService],
+ ['osDevice', async () => (await import('./services/osDeviceProcess.js')).runOsDeviceService],
['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],
['agentCleanup', async () => (await import('./services/agentCleanupProcess.js')).runAgentCleanupService],
['store', async () => (await import('./services/storeProcess.js')).runStoreService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 4a66abd38..947f4bfbc 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -54,7 +54,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens, submission readings, model control, question navigation and Codex's app-server connection (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model- and question-control grants | on demand |
| `search` | search | native `node:sqlite`, the index's memory | always |
| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | on demand |
-| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, agentCleanup, messages | light pure-JS services: isolated from the core, not from each other | always |
+| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, agentCleanup, messages, osDevice | light pure-JS services: isolated from the core, not from each other | always |
| `gateway` | gateway | network, crypto and pure-JS WebRTC: the attack surface | on demand |
| `models` | models | grid's installs, downloads and commands | on demand |
| `devices` | devices, wifi | the dials' serial ports, the fleet's lane, the voice router's worker, the Wi-Fi device | on demand |
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index 2b3346a9f..f65b3e900 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -18,6 +18,7 @@ import { startModels } from './models.js'
import { startMessagesInCore } from './messages.js'
import { startMonitor } from './monitor.js'
import { startOrchestrator } from './orchestrator.js'
+import { startOsDevice } from './osDevice.js'
import { startProjects } from './projects.js'
import { startRecaps } from './recaps.js'
import { startRouter } from './router.js'
@@ -34,6 +35,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 6877e6bda..3b546d84a 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -31,6 +31,7 @@ export { startMessagesInCore } from './messages.js'
export { startModels } from './models.js'
export { startMonitor } from './monitor.js'
export { startOrchestrator } from './orchestrator.js'
+export { startOsDevice } from './osDevice.js'
export { startProjects } from './projects.js'
export { startRecaps } from './recaps.js'
export { startRouter } from './router.js'
diff --git a/cli/src/services/osDevice.spec.ts b/cli/src/services/osDevice.spec.ts
new file mode 100644
index 000000000..7d7a15e8d
--- /dev/null
+++ b/cli/src/services/osDevice.spec.ts
@@ -0,0 +1,224 @@
+import { EventEmitter } from 'node:events'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { encryptDownFrame, encryptRpcResult } from '../lib/e2ee/applicationFrames.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import {
+ activeSsid, execBounded, joinRequest, LIVE_UPDATE, MAX_OUTPUT, nmcliFields, OS_DEVICE_REQUESTS, SETUP, SETUP_RESULT, spawnDetached,
+ startOsDevice, UPDATE_BUSY_MS, updateOf, wifiNetworks, type OsDeviceDeps,
+} from './osDevice.js'
+
+// Nothing real is ever run: the defaults' child_process is this fake.
+const child = vi.hoisted(() => ({ execFile: vi.fn(), spawn: vi.fn() }))
+vi.mock('node:child_process', () => child)
+
+const OWNER = { local: false, owner: true }
+const STATUS = JSON.stringify({
+ runtime: '/var/lib/harness-os/builds/aaa', versions: { hn: '1.2.3', cli: '0.9.1' }, ready: '/var/lib/harness-os/builds/bbb',
+ restart_required: false, system: { available: false, checked_at: 1 }, check: { errors: [] },
+})
+
+function service(over: OsDeviceDeps = {}) {
+ const exec = vi.fn(async (file: string, args: readonly string[]) => {
+ if (file === '/usr/bin/python3') return STATUS
+ if (args.includes('ACTIVE,SSID')) return 'no:Other\nyes:Home\\: 5G\n'
+ return 'Home\\: 5G:70:WPA2:*\nCafe:80:--:\n'
+ })
+ const spawnDetached = vi.fn()
+ let clock = 1_000
+ const deps: OsDeviceDeps = { env: {}, exists: () => true, exec, spawnDetached, now: () => clock, readFile: async () => '{"ok":true,"ssid":"Cafe"}', ...over }
+ const ask = startOsDevice(fakeCore(), deps).os_device!
+ return { ask: (payload: Record<string, unknown>, asker = OWNER) => ask(payload, asker), exec, spawnDetached, tick: (ms: number) => { clock += ms } }
+}
+
+describe('the Harness OS computer, managed from the phone', () => {
+ afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); child.execFile.mockReset(); child.spawn.mockReset() })
+
+ it('answers the one request it declares, and only to the owner', async () => {
+ expect(Object.keys(startOsDevice(fakeCore(), { env: {} }))).toEqual([...OS_DEVICE_REQUESTS])
+ const { ask, exec } = service()
+ expect(await ask({ action: 'status' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await ask({ action: 'reboot' })).toEqual({ error: 'BAD_REQUEST' })
+ expect(await ask({})).toEqual({ error: 'BAD_REQUEST' })
+ expect(exec).not.toHaveBeenCalled()
+ })
+
+ it('is always sealed over the relay: a Wi-Fi join carries the password', () => {
+ expect(encryptDownFrame('os_device')).toBe(true)
+ expect(encryptRpcResult('os_device_result')).toBe(true)
+ })
+
+ it('says a computer is not on Harness OS, and does nothing else there', async () => {
+ const { ask, exec, spawnDetached } = service({ exists: () => false })
+ expect(await ask({ action: 'status' })).toEqual({ harnessOs: false })
+ for (const action of ['update', 'wifi_scan', 'wifi_join', 'wifi_result']) expect(await ask({ action, ssid: 'x' })).toEqual({ error: 'UNSUPPORTED_OS' })
+ expect(exec).not.toHaveBeenCalled()
+ expect(spawnDetached).not.toHaveBeenCalled()
+ })
+
+ it('knows Harness OS by its update tool or HARNESS_OS=1', async () => {
+ const exists = vi.fn(() => false)
+ expect(await service({ exists, env: { HARNESS_OS: '1' } }).ask({ action: 'status' })).toMatchObject({ harnessOs: true })
+ expect(exists).not.toHaveBeenCalled()
+ exists.mockReturnValue(true)
+ expect(await service({ exists, env: { HARNESS_OS: '0' } }).ask({ action: 'status' })).toMatchObject({ harnessOs: true })
+ expect(exists).toHaveBeenCalledWith(LIVE_UPDATE)
+ })
+
+ it('reads the update and the network the computer is on, bounded', async () => {
+ const { ask, exec } = service()
+ expect(await ask({ action: 'status' })).toEqual({ harnessOs: true, update: { available: true, runtime: '0.9.1', version: 'bbb' }, wifi: { ssid: 'Home: 5G' } })
+ expect(exec).toHaveBeenCalledWith('/usr/bin/python3', [LIVE_UPDATE, 'status'], { timeout: 15_000 })
+ expect(exec).toHaveBeenCalledWith('nmcli', ['-t', '-e', 'yes', '-f', 'ACTIVE,SSID', 'device', 'wifi'], { timeout: 10_000 })
+ })
+
+ it('still answers on Harness OS when its update tool or nmcli fails', async () => {
+ const failing = (reason: unknown) => service({ exec: vi.fn(async () => { throw reason }) }).ask({ action: 'status' })
+ expect(await failing(new Error('Command failed: python3\nTraceback ...'))).toEqual({ harnessOs: true, update: { available: false, error: 'Command failed: python3' }, wifi: { ssid: null } })
+ expect(await failing('killed')).toEqual({ harnessOs: true, update: { available: false, error: 'killed' }, wifi: { ssid: null } })
+ const notJson = service({ exec: vi.fn(async () => 'not json') })
+ expect(await notJson.ask({ action: 'status' })).toMatchObject({ update: { available: false, error: expect.stringContaining('JSON') } })
+ const notObject = service({ exec: vi.fn(async () => '[1]') })
+ expect(await notObject.ask({ action: 'status' })).toMatchObject({ update: { available: false, error: 'live_update.py status did not answer an object' } })
+ })
+
+ it('reads an update as available from the system channel or a runtime build ready', () => {
+ expect(updateOf({ runtime: '/b/aaa', ready: null, system: { available: true, version: '2026.10.14' }, versions: {} }))
+ .toEqual({ available: true, runtime: 'aaa', version: '2026.10.14' })
+ expect(updateOf({ runtime: '/b/aaa', ready: '/b/aaa', system: { supported: false, available: false }, restart_required: true }))
+ .toEqual({ available: false, runtime: 'aaa', restartRequired: true })
+ expect(updateOf({ runtime: '/b/aaa', ready: '/b/ccc', system: { available: true } })).toEqual({ available: true, runtime: 'aaa', version: 'ccc' })
+ expect(updateOf({ system: [], versions: [] })).toEqual({ available: false, runtime: null })
+ })
+
+ it('starts the update detached, once in ten minutes', async () => {
+ const { ask, spawnDetached, tick } = service()
+ expect(await ask({ action: 'update' })).toEqual({ started: true })
+ expect(spawnDetached).toHaveBeenCalledWith('/usr/bin/harness', ['update'])
+ tick(UPDATE_BUSY_MS - 1)
+ expect(await ask({ action: 'update' })).toEqual({ error: 'BUSY' })
+ tick(1)
+ expect(await ask({ action: 'update' })).toEqual({ started: true })
+ expect(spawnDetached).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not count an update that could not start', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const spawnDetached = vi.fn((): void => { throw new Error('spawn EAGAIN') })
+ const { ask } = service({ spawnDetached })
+ expect(await ask({ action: 'update' })).toEqual({ error: 'FAILED', message: 'spawn EAGAIN' })
+ spawnDetached.mockImplementation(() => {})
+ expect(await ask({ action: 'update' })).toEqual({ started: true })
+ })
+
+ it('lists the networks it sees, the one in use first', async () => {
+ const { ask, exec } = service()
+ expect(await ask({ action: 'wifi_scan' })).toEqual({ networks: [{ ssid: 'Home: 5G', signal: 70, security: 'WPA2', active: true }, { ssid: 'Cafe', signal: 80, security: '', active: false }] })
+ expect(exec).toHaveBeenCalledWith('nmcli', ['-t', '-e', 'yes', '-f', 'SSID,SIGNAL,SECURITY,IN-USE', 'device', 'wifi', 'list', '--rescan', 'auto'], { timeout: 20_000 })
+ })
+
+ it('answers a scan that failed as a failure', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { ask } = service({ exec: vi.fn(async () => { throw new Error('nmcli: not found') }) })
+ expect(await ask({ action: 'wifi_scan' })).toEqual({ error: 'FAILED', message: 'Could not list Wi-Fi networks: nmcli: not found' })
+ expect(error).toHaveBeenCalledWith('[os-device] wifi_scan failed:', 'Could not list Wi-Fi networks: nmcli: not found')
+ })
+
+ it('joins another network detached, the password on stdin alone', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { ask, spawnDetached } = service()
+ expect(await ask({ action: 'wifi_join', ssid: 'Cafe', password: 'secret-pass' })).toEqual({ started: true })
+ expect(spawnDetached).toHaveBeenCalledWith('sudo', ['-n', '/usr/bin/python3', SETUP, 'join'], '{"ssid":"Cafe","password":"secret-pass"}')
+ expect(await ask({ action: 'wifi_join', ssid: 'Open' })).toEqual({ started: true })
+ expect(spawnDetached).toHaveBeenLastCalledWith('sudo', ['-n', '/usr/bin/python3', SETUP, 'join'], '{"ssid":"Open","password":""}')
+ expect(await ask({ action: 'wifi_join', ssid: '', password: 'secret-pass' })).toEqual({ error: 'BAD_REQUEST', message: 'Choose a Wi-Fi network.' })
+ spawnDetached.mockImplementation(() => { throw new Error('spawn sudo ENOENT') })
+ expect(await ask({ action: 'wifi_join', ssid: 'Cafe', password: 'secret-pass' })).toEqual({ error: 'FAILED', message: 'spawn sudo ENOENT' })
+ expect(JSON.stringify(error.mock.calls)).not.toContain('secret-pass')
+ })
+
+ it('checks a join request before anything runs', () => {
+ expect(joinRequest({ ssid: 7 })).toEqual({ message: 'Choose a Wi-Fi network.' })
+ expect(joinRequest({ ssid: 'é'.repeat(16) })).toEqual({ ssid: 'é'.repeat(16), password: '' })
+ expect(joinRequest({ ssid: 'é'.repeat(17) })).toEqual({ message: 'That network name is too long.' })
+ expect(joinRequest({ ssid: 'a', password: null })).toEqual({ ssid: 'a', password: '' })
+ expect(joinRequest({ ssid: 'a', password: '' })).toEqual({ ssid: 'a', password: '' })
+ expect(joinRequest({ ssid: 'a', password: 12345678 })).toEqual({ message: 'The password must be text.' })
+ expect(joinRequest({ ssid: 'a', password: 'short' })).toEqual({ message: 'A Wi-Fi password has 8 to 63 characters.' })
+ expect(joinRequest({ ssid: 'a', password: 'x'.repeat(64) })).toEqual({ message: 'A Wi-Fi password has 8 to 63 characters.' })
+ expect(joinRequest({ ssid: 'a', password: 'x'.repeat(63) })).toEqual({ ssid: 'a', password: 'x'.repeat(63) })
+ expect(joinRequest({ ssid: 'a', password: 'line\nbreak' })).toEqual({ message: 'A Wi-Fi password cannot contain a line break.' })
+ expect(joinRequest({ ssid: 'a', password: 'line\rbreak' })).toEqual({ message: 'A Wi-Fi password cannot contain a line break.' })
+ })
+
+ it('reads what became of the last join', async () => {
+ const readFile = vi.fn(async () => '{"ok":true,"ssid":"Cafe"}')
+ expect(await service({ readFile }).ask({ action: 'wifi_result' })).toEqual({ result: { ok: true, ssid: 'Cafe' } })
+ expect(readFile).toHaveBeenCalledWith(SETUP_RESULT)
+ expect(await service({ readFile: async () => '"done"' }).ask({ action: 'wifi_result' })).toEqual({ result: null })
+ expect(await service({ readFile: async () => { throw new Error('ENOENT') } }).ask({ action: 'wifi_result' })).toEqual({ result: null })
+ })
+
+ it('reads nmcli\'s terse rows, escapes and all', () => {
+ expect(nmcliFields('a\\:b:c\\\\d:')).toEqual(['a:b', 'c\\d', ''])
+ expect(nmcliFields('trailing\\')).toEqual(['trailing\\'])
+ expect(activeSsid('no:A\r\nyes:\nyes:B\n')).toBe('B')
+ expect(activeSsid('')).toBeNull()
+ expect(wifiNetworks([':90:WPA2:', 'A:40:WPA2:', 'A:60:WPA2:', 'B:x', 'A:50:WPA2:*', 'C:60:WPA1 WPA2: ', 'B:60', 'D'].join('\n'))).toEqual([
+ { ssid: 'A', signal: 60, security: 'WPA2', active: true },
+ { ssid: 'B', signal: 60, security: '', active: false },
+ { ssid: 'C', signal: 60, security: 'WPA1 WPA2', active: false },
+ { ssid: 'D', signal: 0, security: '', active: false },
+ ])
+ })
+
+ it('runs on the real filesystem and environment by default', async () => {
+ vi.stubEnv('HARNESS_OS', '')
+ const requests = startOsDevice(fakeCore())
+ // The development machine is no Harness OS computer; the test reads it as one by its switch below.
+ if (!(await import('node:fs')).existsSync(LIVE_UPDATE)) expect(await requests.os_device!({ action: 'status' }, OWNER)).toEqual({ harnessOs: false })
+ vi.stubEnv('HARNESS_OS', '1')
+ // Read, never written: there is none on a development machine.
+ expect(await requests.os_device!({ action: 'wifi_result' }, OWNER)).toHaveProperty('result')
+ child.spawn.mockReturnValue(Object.assign(new EventEmitter(), { unref: vi.fn() }))
+ expect(await requests.os_device!({ action: 'update' }, OWNER)).toEqual({ started: true })
+ child.execFile.mockImplementation((_f, _a, _o, done: (error: Error | null, stdout: string) => void) => { done(null, 'Home:50::\n'); return { stdin: Object.assign(new EventEmitter(), { end: vi.fn() }) } })
+ expect(await requests.os_device!({ action: 'wifi_scan' }, OWNER)).toEqual({ networks: [{ ssid: 'Home', signal: 50, security: '', active: false }] })
+ })
+})
+
+describe('the defaults that run commands', () => {
+ afterEach(() => { vi.restoreAllMocks(); child.execFile.mockReset(); child.spawn.mockReset() })
+
+ const fakeStdin = () => Object.assign(new EventEmitter(), { end: vi.fn() })
+
+ it('runs a command bounded in time and output, its input on stdin', async () => {
+ const stdin = fakeStdin()
+ child.execFile.mockImplementationOnce((_f, _a, _o, done: (error: Error | null, stdout: string) => void) => { setImmediate(() => done(null, 'out')); return { stdin } })
+ await expect(execBounded('nmcli', ['-t'], { timeout: 5, input: 'in' })).resolves.toBe('out')
+ expect(child.execFile).toHaveBeenCalledWith('nmcli', ['-t'], { timeout: 5, maxBuffer: MAX_OUTPUT, killSignal: 'SIGKILL', encoding: 'utf8' }, expect.any(Function))
+ expect(stdin.end).toHaveBeenCalledWith('in')
+ stdin.emit('error', new Error('EPIPE'))
+ child.execFile.mockImplementationOnce((_f, _a, _o, done: (error: Error | null, stdout: string) => void) => { setImmediate(() => done(new Error('timed out'), '')); return { stdin: fakeStdin() } })
+ await expect(execBounded('nmcli', [], { timeout: 5 })).rejects.toThrow('timed out')
+ })
+
+ it('starts a command detached, its input written and closed, never waited on', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const stdin = fakeStdin()
+ const proc = Object.assign(new EventEmitter(), { stdin, unref: vi.fn() })
+ child.spawn.mockReturnValueOnce(proc)
+ spawnDetached('sudo', ['-n', 'x'], '{"password":"secret-pass"}')
+ expect(child.spawn).toHaveBeenCalledWith('sudo', ['-n', 'x'], { detached: true, stdio: ['pipe', 'ignore', 'ignore'] })
+ expect(stdin.end).toHaveBeenCalledWith('{"password":"secret-pass"}')
+ expect(proc.unref).toHaveBeenCalled()
+ stdin.emit('error', new Error('EPIPE'))
+ proc.emit('error', new Error('spawn sudo ENOENT'))
+ expect(error).toHaveBeenCalledWith('[os-device] could not start sudo:', 'spawn sudo ENOENT')
+ expect(JSON.stringify(error.mock.calls)).not.toContain('secret-pass')
+ const bare = Object.assign(new EventEmitter(), { unref: vi.fn() })
+ child.spawn.mockReturnValueOnce(bare)
+ spawnDetached('/usr/bin/harness', ['update'])
+ expect(child.spawn).toHaveBeenLastCalledWith('/usr/bin/harness', ['update'], { detached: true, stdio: ['ignore', 'ignore', 'ignore'] })
+ expect(bare.unref).toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/services/osDevice.ts b/cli/src/services/osDevice.ts
new file mode 100644
index 000000000..eaccca26b
--- /dev/null
+++ b/cli/src/services/osDevice.ts
@@ -0,0 +1,220 @@
+/**
+ * A Harness OS computer, managed from the owner's phone (`os_device`): whether this computer runs Harness OS,
+ * whether an update is ready and starting it, the Wi-Fi networks it sees, and moving it to another one.
+ *
+ * Owner only. Everything it runs is bounded in time and output, and what must outlive this daemon runs
+ * detached in a process group of its own: the update restarts the daemon, and joining another Wi-Fi drops the
+ * connection the request came over, so both are started and answered `{ started: true }` at once. The join's
+ * result is read afterwards (`wifi_result`), from the file Harness OS's setup writes.
+ *
+ * A Wi-Fi password goes to the setup only on its stdin: never in an argv, a log or an error message.
+ */
+import { execFile, spawn } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
+import { basename } from 'node:path'
+import type { CoreApi, ServiceRequests } from '../core/api.js'
+
+/** The requests this service answers for the apps, declared in core/api.ts for the core to route. */
+export { OS_DEVICE_REQUESTS } from '../core/api.js'
+
+/** Harness OS's own update tool: present on Harness OS alone. */
+export const LIVE_UPDATE = '/usr/lib/harness-os/live_update.py'
+/** Harness OS's setup, which joins a Wi-Fi network from the JSON on its stdin. */
+export const SETUP = '/usr/lib/harness-os/setup.py'
+/** Where the setup writes what became of its last join. */
+export const SETUP_RESULT = '/var/lib/harness-os/setup-result.json'
+export const PYTHON = '/usr/bin/python3'
+export const HARNESS = '/usr/bin/harness'
+export const NMCLI = 'nmcli'
+/** How long an update counts as started: a second one inside it is refused BUSY. */
+export const UPDATE_BUSY_MS = 10 * 60_000
+export const STATUS_TIMEOUT_MS = 15_000
+export const NMCLI_TIMEOUT_MS = 10_000
+export const SCAN_TIMEOUT_MS = 20_000
+/** The most output a command run here may print before it is stopped. */
+export const MAX_OUTPUT = 1024 * 1024
+
+type Payload = Record<string, unknown>
+
+export interface ExecOptions { timeout: number; input?: string }
+
+export interface OsDeviceDeps {
+ env?: Record<string, string | undefined>
+ exists?: (path: string) => boolean
+ readFile?: (path: string) => Promise<string>
+ /** Run [file] with [args], bounded by [options.timeout] and MAX_OUTPUT; its stdout, or a rejection. */
+ exec?: (file: string, args: readonly string[], options: ExecOptions) => Promise<string>
+ /** Start [file] detached from this daemon (its own process group, no output), [input] written to its stdin. */
+ spawnDetached?: (file: string, args: readonly string[], input?: string) => void
+ now?: () => number
+}
+
+/** Run a command, bounded in time and output (core/AGENTS.md rule 4). */
+export function execBounded(file: string, args: readonly string[], options: ExecOptions): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = execFile(file, [...args], { timeout: options.timeout, maxBuffer: MAX_OUTPUT, killSignal: 'SIGKILL', encoding: 'utf8' },
+ (error, stdout) => { if (error) reject(error); else resolve(stdout) })
+ child.stdin!.on('error', () => { /* a command that exits before reading its input */ })
+ child.stdin!.end(options.input)
+ })
+}
+
+/** Start a command that outlives this daemon: its own process group, its output dropped, never waited on. */
+export function spawnDetached(file: string, args: readonly string[], input?: string): void {
+ const child = spawn(file, [...args], { detached: true, stdio: [input === undefined ? 'ignore' : 'pipe', 'ignore', 'ignore'] })
+ // Its argv only: the input may hold a Wi-Fi password.
+ child.on('error', (error) => console.error(`[os-device] could not start ${file}:`, short(error)))
+ if (input !== undefined) {
+ child.stdin!.on('error', () => { /* the command exited before reading it */ })
+ child.stdin!.end(input)
+ }
+ child.unref()
+}
+
+/** One `nmcli -t -e yes` row's fields: split on an unescaped `:`, with `\:` and `\\` read as `:` and `\`. */
+export function nmcliFields(line: string): string[] {
+ const fields: string[] = []
+ let field = ''
+ for (let i = 0; i < line.length; i++) {
+ const c = line[i]
+ if (c === '\\' && i + 1 < line.length) field += line[++i]
+ else if (c === ':') { fields.push(field); field = '' } else field += c
+ }
+ fields.push(field)
+ return fields
+}
+
+const rows = (out: string): string[][] => out.split('\n').map((line) => line.replace(/\r$/, '')).filter(Boolean).map(nmcliFields)
+
+/** The network this computer is on, from `nmcli -t -e yes -f ACTIVE,SSID device wifi`; null when none. */
+export function activeSsid(out: string): string | null {
+ return rows(out).find(([active, ssid]) => active === 'yes' && !!ssid)?.[1] ?? null
+}
+
+export interface WifiNetwork { ssid: string; signal: number; security: string; active: boolean }
+
+/** The networks in `nmcli -t -e yes -f SSID,SIGNAL,SECURITY,IN-USE device wifi list`: one per name (its
+ * strongest), hidden ones left out, the one in use first and then the strongest. */
+export function wifiNetworks(out: string): WifiNetwork[] {
+ const byName = new Map<string, WifiNetwork>()
+ for (const [ssid, signalText, security = '', inUse = ''] of rows(out)) {
+ if (!ssid) continue
+ const signal = Number.parseInt(signalText ?? '', 10)
+ const row: WifiNetwork = { ssid, signal: Number.isFinite(signal) ? signal : 0, security: security === '--' ? '' : security, active: inUse.trim() === '*' }
+ const known = byName.get(ssid)
+ if (!known) { byName.set(ssid, row); continue }
+ const active = known.active || row.active
+ byName.set(ssid, { ...(row.signal > known.signal ? row : known), active })
+ }
+ return [...byName.values()].sort((a, b) => Number(b.active) - Number(a.active) || b.signal - a.signal || a.ssid.localeCompare(b.ssid))
+}
+
+const short = (error: unknown): string => String(error instanceof Error ? error.message : error).split('\n')[0].slice(0, 200)
+const record = (value: unknown): value is Payload => !!value && typeof value === 'object' && !Array.isArray(value)
+
+/** What the phone shows of `live_update.py status`: whether an update is ready, the version running and the new one. */
+export function updateOf(status: Payload): Payload {
+ const runtime = typeof status.runtime === 'string' ? status.runtime : null
+ const ready = typeof status.ready === 'string' ? status.ready : null
+ const system = record(status.system) ? status.system : {}
+ const versions = record(status.versions) ? status.versions : {}
+ const runtimeReady = ready !== null && ready !== runtime
+ const update: Payload = {
+ available: system.available === true || runtimeReady,
+ runtime: typeof versions.cli === 'string' ? versions.cli : runtime === null ? null : basename(runtime),
+ }
+ const version = system.available === true && typeof system.version === 'string' ? system.version : runtimeReady ? basename(ready) : undefined
+ if (version !== undefined) update.version = version
+ if (status.restart_required === true) update.restartRequired = true
+ return update
+}
+
+/** The Wi-Fi join's request, checked: a name of 1 to 32 bytes, and no password (an open network) or one of 8 to 63
+ * characters on one line. The reason it is refused otherwise, for a person to read. */
+export function joinRequest(payload: Payload): { ssid: string; password: string } | { message: string } {
+ const { ssid, password } = payload
+ if (typeof ssid !== 'string' || ssid.length === 0) return { message: 'Choose a Wi-Fi network.' }
+ if (Buffer.byteLength(ssid, 'utf8') > 32) return { message: 'That network name is too long.' }
+ if (password === undefined || password === null || password === '') return { ssid, password: '' }
+ if (typeof password !== 'string') return { message: 'The password must be text.' }
+ if (password.length < 8 || password.length > 63) return { message: 'A Wi-Fi password has 8 to 63 characters.' }
+ if (/[\r\n]/.test(password)) return { message: 'A Wi-Fi password cannot contain a line break.' }
+ return { ssid, password }
+}
+
+export function startOsDevice(_core: CoreApi, deps: OsDeviceDeps = {}): ServiceRequests {
+ const env = deps.env ?? process.env
+ const exists = deps.exists ?? existsSync
+ const read = deps.readFile ?? ((path: string) => readFile(path, 'utf8'))
+ const exec = deps.exec ?? execBounded
+ const detached = deps.spawnDetached ?? spawnDetached
+ const now = deps.now ?? Date.now
+ let updateStartedAt: number | null = null
+
+ const harnessOs = (): boolean => env.HARNESS_OS === '1' || exists(LIVE_UPDATE)
+
+ const currentSsid = async (): Promise<string | null> =>
+ activeSsid(await exec(NMCLI, ['-t', '-e', 'yes', '-f', 'ACTIVE,SSID', 'device', 'wifi'], { timeout: NMCLI_TIMEOUT_MS }).catch(() => ''))
+
+ const status = async (): Promise<Payload> => {
+ if (!harnessOs()) return { harnessOs: false }
+ const [update, ssid] = await Promise.all([
+ exec(PYTHON, [LIVE_UPDATE, 'status'], { timeout: STATUS_TIMEOUT_MS }).then((out) => {
+ const parsed: unknown = JSON.parse(out)
+ if (!record(parsed)) throw new Error('live_update.py status did not answer an object')
+ return updateOf(parsed)
+ }).catch((error: unknown) => ({ available: false, error: short(error) })),
+ currentSsid(),
+ ])
+ return { harnessOs: true, update, wifi: { ssid } }
+ }
+
+ const update = (): Payload => {
+ if (updateStartedAt !== null && now() - updateStartedAt < UPDATE_BUSY_MS) return { error: 'BUSY' }
+ detached(HARNESS, ['update'])
+ updateStartedAt = now()
+ return { started: true }
+ }
+
+ const scan = async (): Promise<Payload> => {
+ const out = await exec(NMCLI, ['-t', '-e', 'yes', '-f', 'SSID,SIGNAL,SECURITY,IN-USE', 'device', 'wifi', 'list', '--rescan', 'auto'], { timeout: SCAN_TIMEOUT_MS })
+ .catch((error: unknown) => { throw new Error(`Could not list Wi-Fi networks: ${short(error)}`) })
+ return { networks: wifiNetworks(out) }
+ }
+
+ const join = (payload: Payload): Payload => {
+ const request = joinRequest(payload)
+ if ('message' in request) return { error: 'BAD_REQUEST', message: request.message }
+ // The reply goes out before the computer leaves its network; the password only on the setup's stdin.
+ detached('sudo', ['-n', PYTHON, SETUP, 'join'], JSON.stringify({ ssid: request.ssid, password: request.password }))
+ return { started: true }
+ }
+
+ const result = async (): Promise<Payload> => {
+ try {
+ const parsed: unknown = JSON.parse(await read(SETUP_RESULT))
+ return { result: record(parsed) ? parsed : null }
+ } catch { return { result: null } }
+ }
+
+ return {
+ os_device: async (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ const action = payload.action
+ if (action === 'status') return status()
+ if (action !== 'update' && action !== 'wifi_scan' && action !== 'wifi_join' && action !== 'wifi_result') return { error: 'BAD_REQUEST' }
+ if (!harnessOs()) return { error: 'UNSUPPORTED_OS' }
+ try {
+ if (action === 'update') return update()
+ if (action === 'wifi_scan') return await scan()
+ if (action === 'wifi_join') return join(payload)
+ return await result()
+ } catch (error) {
+ // Never the payload: it may hold a Wi-Fi password.
+ console.error(`[os-device] ${action} failed:`, short(error))
+ return { error: 'FAILED', message: short(error) }
+ }
+ },
+ }
+}
diff --git a/cli/src/services/osDeviceProcess.spec.ts b/cli/src/services/osDeviceProcess.spec.ts
new file mode 100644
index 000000000..90ce1746b
--- /dev/null
+++ b/cli/src/services/osDeviceProcess.spec.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { OS_DEVICE_REQUESTS } from '../core/api.js'
+import { runServiceProcess, type ServiceProcessOptions } from './process.js'
+import { runOsDeviceService } from './osDeviceProcess.js'
+
+// The real default reaches a real socket: never in a test.
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+
+describe('the Harness OS computer\'s management in its own process', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ it('answers with the same handler as in the core\'s process', async () => {
+ let options: ServiceProcessOptions | null = null
+ const service = { stop: vi.fn() }
+ const handle = runOsDeviceService({
+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
+ run: (given) => { options = given; return service },
+ start: () => ({ os_device: async () => ({ harnessOs: false }) }),
+ })
+ expect(handle).toBe(service)
+ expect(options).toMatchObject({ name: 'osDevice', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(await options!.requests.os_device!({ action: 'status' }, { local: true, owner: true })).toEqual({ harnessOs: false })
+ })
+
+ it('runs as a real service by default, answering every request the core routes to it', () => {
+ runOsDeviceService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ const options = vi.mocked(runServiceProcess).mock.calls.at(-1)![0]
+ expect(options.name).toBe('osDevice')
+ expect(Object.keys(options.requests)).toEqual([...OS_DEVICE_REQUESTS])
+ })
+})
diff --git a/cli/src/services/osDeviceProcess.ts b/cli/src/services/osDeviceProcess.ts
new file mode 100644
index 000000000..a79923b11
--- /dev/null
+++ b/cli/src/services/osDeviceProcess.ts
@@ -0,0 +1,29 @@
+/**
+ * The Harness OS computer's management in its own process (`harness __service osDevice`, in the edge host): the
+ * same handler as in the core's process (services/osDevice.ts). It asks the core nothing; the commands it runs
+ * are this process's alone, and those that must outlive it (an update, a Wi-Fi join) run detached.
+ */
+import { startOsDevice } from './osDevice.js'
+import { runServiceProcess, type ServiceProcess } from './process.js'
+import { processCoreApi } from './processCoreApi.js'
+
+export interface OsDeviceServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ /** Swapped in tests for one that does not touch the real socket or process. */
+ run?: typeof runServiceProcess
+ /** Swapped in tests for one that runs no command. */
+ start?: typeof startOsDevice
+}
+
+export function runOsDeviceService(options: OsDeviceServiceOptions): ServiceProcess {
+ return (options.run ?? runServiceProcess)({
+ name: 'osDevice',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ requests: (options.start ?? startOsDevice)(processCoreApi(options.dataDir, 'osDevice')),
+ })
+}
diff --git a/os/installer.py b/os/installer.py
index 3f52f773f..a3577975a 100644
--- a/os/installer.py
+++ b/os/installer.py
@@ -517,7 +517,8 @@ def install_image(config, source, target, progress, resources):
networks = Path('/etc/NetworkManager/system-connections')
if networks.exists():
shutil.copytree(networks, target / 'etc/NetworkManager/system-connections', dirs_exist_ok=True)
- chroot(target, 'systemctl', 'enable', 'NetworkManager', 'systemd-resolved', 'systemd-timesyncd')
+ chroot(target, 'systemctl', 'enable', 'NetworkManager', 'systemd-resolved', 'systemd-timesyncd',
+ 'harness-setup.service')
chroot(target, 'systemctl', 'disable', 'sshd.service')
report('Preparing startup and recovery…')
chroot(target, '/usr/lib/harness-os/init-keyring')
diff --git a/os/network.py b/os/network.py
index 62171e201..354737e60 100644
--- a/os/network.py
+++ b/os/network.py
@@ -2,13 +2,18 @@
"""A full-page Wi-Fi step backed by NetworkManager, with no resident UI service."""
import argparse
import curses
+import json
import os
+from pathlib import Path
import subprocess
import time
import uuid
import unicodedata
WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
+# setup.py's hotspot for a phone, and the Wi-Fi it saw before taking the radio.
+SETUP_HOTSPOT = 'harness-setup'
+SETUP_NETWORKS = '/run/harness-os/setup-networks.json'
def nmcli(*args, secret=None, wait=8):
@@ -36,15 +41,44 @@ def fields(line):
return [*values, value]
+def setup_hotspot_up():
+ """Whether the radio hosts setup.py's hotspot for a phone. It is not a network this computer is
+ on, and while it is up the radio cannot scan: the list shown is the one setup.py read first."""
+ try:
+ result = nmcli('-t', '-e', 'yes', '-f', 'NAME', 'connection', 'show', '--active', wait=3)
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return result.returncode == 0 and SETUP_HOTSPOT in [fields(line)[0] for line in result.stdout.splitlines()]
+
+
def connected():
try:
result = nmcli('-t', '-f', 'STATE', 'general', wait=2)
- return result.returncode == 0 and result.stdout.strip().startswith('connected')
+ if result.returncode or not result.stdout.strip().startswith('connected'):
+ return False
except (OSError, subprocess.TimeoutExpired):
return False
+ # The setup hotspot alone makes NetworkManager say connected (local only): not online.
+ if not setup_hotspot_up():
+ return True
+ return any(row[1] == 'ethernet' and row[2] == 'connected' for row in wired_devices())
+
+
+def setup_networks():
+ """What the radio saw before it became the setup hotspot (os/setup.py)."""
+ try:
+ rows = json.loads(Path(SETUP_NETWORKS).read_text())
+ except (OSError, ValueError):
+ return []
+ networks = [dict(ssid=row['ssid'], signal=int(row['signal']), security=row.get('security') or '--',
+ device=row['device'], bssid='', active=False)
+ for row in rows if isinstance(row, dict) and row.get('ssid') and row.get('device')]
+ return sorted(networks, key=lambda row: (-row['signal'], row['ssid']))
def scan(rescan=None):
+ if setup_hotspot_up():
+ return setup_networks()
# Opening the page should reuse a recent scan, especially just after a
# reconnect. NetworkManager refreshes results older than 30 seconds in auto
# mode. Force a scan only when the user chooses Rescan.
@@ -128,9 +162,17 @@ def saved_connection(network):
return None
+def leave_setup_hotspot():
+ # Chosen here, on the screen: the radio stops hosting the phone's setup hotspot to join it, and
+ # setup.py, seeing this computer online, stops waiting for the phone.
+ if setup_hotspot_up():
+ nmcli('connection', 'down', 'id', SETUP_HOTSPOT, wait=10)
+
+
def connect(network, password=None):
saved = saved_connection(network) if password is None else None
if saved:
+ leave_setup_hotspot()
return nmcli('connection', 'up', 'uuid', saved, 'ifname', network['device'], wait=30).returncode == 0
security = network['security']
protected = bool(security and security != '--')
@@ -147,6 +189,7 @@ def connect(network, password=None):
if protected:
key = 'sae' if 'WPA3' in security and 'WPA2' not in security else 'wpa-psk'
arguments += ['wifi-sec.key-mgmt', key, 'wifi-sec.psk-flags', '0']
+ leave_setup_hotspot()
created = nmcli(*arguments)
if created.returncode:
raise ValueError('Could not configure Wi-Fi. Choose Rescan and try again.')
diff --git a/os/packages.x86_64 b/os/packages.x86_64
index b6b9dfb60..669d839d0 100644
--- a/os/packages.x86_64
+++ b/os/packages.x86_64
@@ -25,6 +25,7 @@ sudo
python
openssh
networkmanager
+dnsmasq
systemd-resolvconf
zram-generator
wireless-regdb
diff --git a/os/root/etc/pacman.d/hooks/40-harness-setup.hook b/os/root/etc/pacman.d/hooks/40-harness-setup.hook
new file mode 100644
index 000000000..fdf2b740d
--- /dev/null
+++ b/os/root/etc/pacman.d/hooks/40-harness-setup.hook
@@ -0,0 +1,10 @@
+[Trigger]
+Operation = Install
+Operation = Upgrade
+Type = Path
+Target = usr/lib/systemd/system/harness-setup.service
+
+[Action]
+Description = Enabling phone setup for when Harness has no network
+When = PostTransaction
+Exec = /usr/bin/sh -c 'test -e /etc/harness-live || systemctl enable --now harness-setup.service'
diff --git a/os/root/etc/sudoers.d/20-harness-network b/os/root/etc/sudoers.d/20-harness-network
index 02a10a58b..573d83f88 100644
--- a/os/root/etc/sudoers.d/20-harness-network
+++ b/os/root/etc/sudoers.d/20-harness-network
@@ -1,3 +1,6 @@
# A local user may configure networking without another password prompt.
# Both commands run the fixed, root-owned network form; no arbitrary command is accepted.
%wheel ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/network.py, /usr/bin/python3 /usr/lib/harness-os/network.py --first-use
+# The daemon switching Wi-Fi for the person's phone (cli services/osDevice.ts): the Wi-Fi comes as JSON
+# on stdin to the fixed, root-owned setup helper, which goes back to the previous Wi-Fi when it fails.
+%wheel ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/setup.py join
diff --git a/os/root/usr/lib/systemd/system/harness-setup.service b/os/root/usr/lib/systemd/system/harness-setup.service
new file mode 100644
index 000000000..5f33d6b35
--- /dev/null
+++ b/os/root/usr/lib/systemd/system/harness-setup.service
@@ -0,0 +1,16 @@
+[Unit]
+Description=Set this Harness up from a phone while it has no network
+After=NetworkManager.service
+Wants=NetworkManager.service
+ConditionPathExists=!/etc/harness-live
+
+[Service]
+Type=simple
+ExecStart=/usr/bin/python3 /usr/lib/harness-os/setup.py watch
+# Leave no setup hotspot behind when stopped mid-way.
+ExecStopPost=-/usr/bin/nmcli connection delete id harness-setup
+Restart=on-failure
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
diff --git a/os/setup.py b/os/setup.py
new file mode 100644
index 000000000..4843e61fa
--- /dev/null
+++ b/os/setup.py
@@ -0,0 +1,636 @@
+#!/usr/bin/env python3
+"""Set up a Harness with no screen from a phone: a setup hotspot, the Wi-Fi this computer sees,
+the person's Wi-Fi and password, and a sign-in ticket for the phone's account.
+
+The phone (mobile/lib/phone/add_device/) asks the backend for a ticket while it still has the
+Internet, joins the open hotspot `Harness-XXXX` (the person picks it from a list), and talks to
+http://10.42.0.1/setup. This computer then leaves the hotspot, joins the chosen Wi-Fi, checks the
+Internet and signs in with `harness login --ticket`. When the Wi-Fi fails, the hotspot comes back
+with the reason (wrong password, out of reach, no address, no Internet), for the phone to read when
+it rejoins, and the person tries again.
+
+The hotspot comes up by itself only on a computer with no screen, and only while there is no
+network: soon after starting, and after a long outage later (a new router). A laptop keeps its own
+Wi-Fi page. While nobody is on it, saved Wi-Fi is tried again every few minutes, so a
+router that was only off brings the computer back by itself.
+
+The hotspot has no password, for setup to be one tap: whoever is in range of a computer in setup
+can choose its Wi-Fi, and the Wi-Fi password crosses an open network. Nothing here runs a command
+the phone names, and a computer already signed in keeps its account (`login --ticket` refuses).
+"""
+import argparse
+import http.server
+import importlib.util
+import json
+from pathlib import Path
+import pwd
+import queue
+import socket
+import subprocess
+import sys
+import threading
+import time
+import uuid
+
+STATE = Path('/var/lib/harness-os')
+RESULT = STATE / 'setup-result.json'
+NOW = Path('/run/harness-os/setup-now')
+# What the radio saw before hosting the hotspot, for the screen's Wi-Fi page (network.py SETUP_NETWORKS).
+SCREEN_NETWORKS = Path('/run/harness-os/setup-networks.json')
+HEADLESS = Path('/etc/harness-os/headless')
+DRM = Path('/sys/class/drm')
+USER = 'me'
+HOME = Path('/home') / USER
+SESSION = HOME / '.harness/auth/session.json'
+COMPUTER_ID = HOME / '.harness/computer-id'
+HOTSPOT = 'harness-setup'
+ADDRESS = '10.42.0.1'
+PORT = 80
+PROTOCOL = 1
+# Saved Wi-Fi gets this long to come back before the hotspot takes the radio.
+OFFLINE_AT_START = 60
+OFFLINE_LATER = 600
+# With nobody on the hotspot, saved Wi-Fi is tried again this often, for this long.
+RETRY_SAVED = 300
+SAVED_JOIN = 45
+JOIN = 45
+INTERNET_WAIT = 30
+# Refusals of the key before a join is called a wrong password, without waiting out JOIN.
+WRONG_KEYS = 2
+INTERNET = ('harness-api.autonomous.ai', 443)
+
+MESSAGES = {
+ 'WRONG_PASSWORD': 'The password for "{ssid}" is not right. Passwords are case-sensitive.',
+ 'NOT_FOUND': '"{ssid}" is out of reach. Move the device closer to the router, or check the name.',
+ 'NO_ADDRESS': 'Joined "{ssid}", but the router gave no address. Restart the router and try again.',
+ 'TIMEOUT': 'Joining "{ssid}" took too long. Move the device closer to the router and try again.',
+ 'NO_INTERNET': 'Joined "{ssid}", but it does not reach the Internet. A sign-in page or a firewall may be in the way.',
+ 'WIFI': 'Could not join "{ssid}". Try again.',
+}
+
+
+def load_network():
+ spec = importlib.util.spec_from_file_location('harness_os_network', Path(__file__).with_name('network.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+network = load_network()
+nmcli = network.nmcli
+
+
+def log(message):
+ print(f'harness-setup: {message}', flush=True)
+
+
+
+def computer_id():
+ for path in [COMPUTER_ID, Path('/etc/machine-id')]:
+ try:
+ value = path.read_text().strip()
+ if value:
+ return value
+ except OSError:
+ pass
+ return ''
+
+
+def hotspot_name():
+ tail = ''.join(character for character in computer_id() if character.isalnum())[-4:].upper()
+ return 'Harness-' + (tail or 'Setup')
+
+
+def signed_in():
+ return SESSION.is_file()
+
+
+def rows(*args, wait=3):
+ try:
+ result = nmcli('-t', '-e', 'yes', *args, wait=wait)
+ except (OSError, subprocess.TimeoutExpired):
+ return []
+ return [] if result.returncode else [network.fields(line) for line in result.stdout.splitlines()]
+
+
+def wifi_device():
+ return next((row[0] for row in rows('-f', 'DEVICE,TYPE', 'device', 'status') if len(row) == 2 and row[1] == 'wifi'), None)
+
+
+def online():
+ """A Wi-Fi or wired connection that is not the setup hotspot."""
+ return any(len(row) == 2 and row[0] != HOTSPOT and row[1] in ('802-11-wireless', '802-3-ethernet')
+ for row in rows('-f', 'NAME,TYPE', 'connection', 'show', '--active'))
+
+
+def saved_wifi():
+ return any(len(row) == 2 and row[0] != HOTSPOT and row[1] == '802-11-wireless'
+ for row in rows('-f', 'NAME,TYPE', 'connection', 'show'))
+
+
+def internet(wait=INTERNET_WAIT):
+ deadline = time.monotonic() + wait
+ while True:
+ try:
+ socket.create_connection(INTERNET, timeout=5).close()
+ return True
+ except OSError:
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(2)
+
+
+def visible_networks(own):
+ try:
+ found = network.scan(rescan=True)
+ except (OSError, subprocess.TimeoutExpired, ValueError):
+ return []
+ seen, networks = set(), []
+ for row in found:
+ if row['ssid'] == own or row['ssid'] in seen:
+ continue
+ seen.add(row['ssid'])
+ security = row['security'] if row['security'] != '--' else ''
+ networks.append(dict(ssid=row['ssid'], signal=row['signal'], security=security))
+ return networks
+
+
+def start_hotspot(device, name):
+ nmcli('connection', 'delete', 'id', HOTSPOT)
+ # Open: the person picks `Harness-XXXX` from a list and nothing more.
+ created = nmcli('connection', 'add', 'type', 'wifi', 'ifname', device, 'con-name', HOTSPOT,
+ 'connection.autoconnect', 'no', 'ssid', name, 'mode', 'ap',
+ # 2.4 GHz: every phone sees it, and it avoids radar channels a client cannot host.
+ '802-11-wireless.band', 'bg',
+ 'ipv4.method', 'shared', 'ipv4.addresses', ADDRESS + '/24', 'ipv6.method', 'disabled')
+ if created.returncode:
+ log('could not create the hotspot: ' + created.stderr.strip())
+ return False
+ up = nmcli('connection', 'up', 'id', HOTSPOT, 'ifname', device, wait=30)
+ if up.returncode:
+ log('could not start the hotspot: ' + up.stderr.strip())
+ nmcli('connection', 'delete', 'id', HOTSPOT)
+ return False
+ return True
+
+
+def stop_hotspot():
+ nmcli('connection', 'down', 'id', HOTSPOT)
+ nmcli('connection', 'delete', 'id', HOTSPOT)
+
+
+def phones_on(device):
+ """Whether a phone is joined to the hotspot; unknown counts as yes, so nobody is cut off."""
+ try:
+ result = subprocess.run(['/usr/bin/iw', 'dev', device, 'station', 'dump'],
+ capture_output=True, text=True, timeout=5)
+ except (OSError, subprocess.TimeoutExpired):
+ return True
+ return result.returncode != 0 or 'Station ' in result.stdout
+
+
+def read_result():
+ try:
+ return json.loads(RESULT.read_text())
+ except (OSError, ValueError):
+ return {}
+
+
+def write_result(**fields):
+ STATE.mkdir(parents=True, exist_ok=True)
+ fields['at'] = int(time.time())
+ partial = RESULT.with_name(RESULT.name + '.partial')
+ partial.write_text(json.dumps(fields) + '\n')
+ partial.replace(RESULT)
+
+
+def reason(output):
+ """NetworkManager's activation failure, as one of MESSAGES."""
+ text = output.lower()
+ if 'secrets were required' in text or 'no-secrets' in text:
+ return 'WRONG_PASSWORD'
+ if 'could not be found' in text or 'no network with ssid' in text:
+ return 'NOT_FOUND'
+ if 'ip configuration' in text or 'dhcp' in text:
+ return 'NO_ADDRESS'
+ if 'timeout' in text or 'timed out' in text:
+ return 'TIMEOUT'
+ return 'WIFI'
+
+
+def wrong_keys(since):
+ """How many times the router refused the key since [since], by wpa_supplicant's own words."""
+ try:
+ result = subprocess.run(['/usr/bin/journalctl', '-t', 'wpa_supplicant', '-o', 'cat', '--no-pager',
+ '--since', f'@{int(since)}'], capture_output=True, text=True, timeout=5)
+ except (OSError, subprocess.TimeoutExpired):
+ return 0
+ # One `CTRL-EVENT-SSID-TEMP-DISABLED … reason=WRONG_KEY` per refusal.
+ return result.stdout.count('reason=WRONG_KEY')
+
+
+def connect(ssid, password, security, device):
+ """Join one Wi-Fi with a new profile, kept only when it works. None, or the reason it failed."""
+ identity = str(uuid.uuid4())
+ arguments = ['connection', 'add', 'type', 'wifi', 'ifname', device, 'con-name', ssid,
+ 'connection.uuid', identity, 'connection.autoconnect', 'no', 'ssid', ssid]
+ if security:
+ key = 'sae' if 'WPA3' in security and 'WPA2' not in security else 'wpa-psk'
+ arguments += ['wifi-sec.key-mgmt', key, 'wifi-sec.psk-flags', '0']
+ # A network missing from the scan may be hidden: ask for it by name.
+ arguments += ['802-11-wireless.hidden', 'yes']
+ created = nmcli(*arguments)
+ if created.returncode:
+ return 'WIFI'
+ kept = False
+ try:
+ arguments = ['connection', 'up', 'uuid', identity, 'ifname', device]
+ secret = None
+ if security:
+ arguments += ['passwd-file', '/dev/stdin']
+ secret = '802-11-wireless-security.psk:' + password + '\n'
+ # A wrong password does not fail NetworkManager: it hands the same key over again and again
+ # until the wait runs out, and then says only "Timeout". wpa_supplicant says it at once
+ # (WRONG_KEY): watched beside the attempt, two of those end it early.
+ started = time.time()
+ attempt = {}
+
+ def up():
+ try:
+ attempt['result'] = nmcli(*arguments, secret=secret, wait=JOIN)
+ except subprocess.TimeoutExpired:
+ attempt['result'] = None
+
+ worker = threading.Thread(target=up, daemon=True)
+ worker.start()
+ wrong = 0
+ while worker.is_alive():
+ worker.join(2)
+ wrong = wrong_keys(started)
+ if worker.is_alive() and wrong >= WRONG_KEYS:
+ nmcli('connection', 'down', 'uuid', identity)
+ worker.join(10)
+ break
+ if wrong >= WRONG_KEYS or (wrong and attempt.get('result') is None):
+ return 'WRONG_PASSWORD'
+ result = attempt.get('result')
+ if result is None:
+ return 'TIMEOUT'
+ if result.returncode:
+ log('NetworkManager: ' + (result.stderr or result.stdout).strip()[-300:])
+ return 'WRONG_PASSWORD' if wrong_keys(started) else reason(result.stderr + result.stdout)
+ if nmcli('connection', 'modify', 'uuid', identity, 'connection.autoconnect', 'yes').returncode:
+ return 'WIFI'
+ kept = True
+ # An older profile for the same Wi-Fi holds the old password: it would win the next reconnect.
+ for row in rows('-f', 'UUID,TYPE', 'connection', 'show'):
+ if len(row) == 2 and row[0] != identity and row[1] == '802-11-wireless':
+ named = nmcli('-g', '802-11-wireless.ssid', 'connection', 'show', 'uuid', row[0])
+ if named.returncode == 0 and named.stdout.rstrip('\n') == ssid:
+ nmcli('connection', 'delete', 'uuid', row[0])
+ return None
+ finally:
+ if not kept:
+ nmcli('connection', 'down', 'uuid', identity)
+ nmcli('connection', 'delete', 'uuid', identity)
+
+
+def forget(ssid):
+ """The profile this attempt saved, when it reached the Wi-Fi but not the Internet."""
+ saved = network.saved_connection(dict(ssid=ssid))
+ if saved:
+ nmcli('connection', 'delete', 'uuid', saved)
+
+
+def sign_in(ticket):
+ if signed_in():
+ return True, ''
+ try:
+ result = subprocess.run(['/usr/bin/runuser', '-u', USER, '--', '/usr/bin/harness', 'login', '--json',
+ '--ticket=' + ticket],
+ capture_output=True, text=True, timeout=90,
+ env=dict(HOME=str(HOME), USER=USER, LOGNAME=USER,
+ PATH='/usr/local/bin:/usr/bin:/bin',
+ XDG_RUNTIME_DIR=f'/run/user/{pwd.getpwnam(USER).pw_uid}'))
+ except (OSError, KeyError, subprocess.TimeoutExpired) as error:
+ return False, str(error)
+ if result.returncode == 0:
+ return True, ''
+ message = ''
+ for line in result.stdout.splitlines():
+ try:
+ message = json.loads(line).get('message') or message
+ except (ValueError, AttributeError):
+ pass
+ return False, message or result.stderr.strip()[-200:] or 'The sign-in failed.'
+
+
+def join(request, networks, device):
+ """Leave the hotspot for the person's Wi-Fi. Returns the result the phone reads."""
+ ssid, password, ticket = request['ssid'], request.get('password') or '', request.get('ticket')
+ seen = next((row for row in networks if row['ssid'] == ssid), None)
+ security = seen['security'] if seen else ('WPA2' if password else '')
+ log(f'joining "{ssid}"')
+ started = time.monotonic()
+ failed = connect(ssid, password, security, device)
+ if not failed and not internet():
+ forget(ssid)
+ failed = 'NO_INTERNET'
+ if failed:
+ log(f'"{ssid}" failed after {int(time.monotonic() - started)}s: {failed}')
+ return dict(state='failed', error=failed, ssid=ssid, message=MESSAGES[failed].format(ssid=ssid))
+ if ticket:
+ ok, message = sign_in(ticket)
+ if not ok:
+ log('sign-in failed: ' + message)
+ return dict(state='done', ssid=ssid, signedIn=False, error='SIGN_IN', message=message)
+ log(f'on "{ssid}" after {int(time.monotonic() - started)}s')
+ return dict(state='done', ssid=ssid, signedIn=signed_in())
+
+
+def check_request(body):
+ if not isinstance(body, dict):
+ return 'Send a JSON object.'
+ ssid, password, ticket = body.get('ssid'), body.get('password'), body.get('ticket')
+ if not isinstance(ssid, str) or not ssid or len(ssid.encode()) > 32:
+ return 'Choose a Wi-Fi network.'
+ if password not in (None, ''):
+ if not isinstance(password, str) or '\n' in password or '\r' in password:
+ return 'That Wi-Fi password cannot be used.'
+ if not 8 <= len(password) <= 63:
+ return 'A Wi-Fi password has 8 to 63 characters.'
+ if ticket is not None and (not isinstance(ticket, str) or not ticket.isprintable() or len(ticket) > 256):
+ return 'That sign-in ticket cannot be used.'
+ return None
+
+
+class Setup:
+ """One stay on the hotspot: the page answering, until the phone sends a Wi-Fi."""
+
+ def __init__(self, name, networks, run):
+ self.name, self.networks, self.run = name, networks, run
+ self.requests = queue.Queue()
+
+ def info(self):
+ return dict(protocol=PROTOCOL, name=socket.gethostname(), hotspot=self.name, run=self.run,
+ computerId=computer_id(), signedIn=signed_in(), result=read_result())
+
+ def handler(self):
+ setup = self
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ server_version = 'HarnessSetup/1'
+
+ def log_message(self, format, *args):
+ pass
+
+ def reply(self, status, body):
+ data = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.send_header('Cache-Control', 'no-store')
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_GET(self):
+ if self.path == '/setup':
+ return self.reply(200, setup.info())
+ if self.path == '/setup/networks':
+ return self.reply(200, dict(networks=setup.networks))
+ self.reply(404, dict(error='NOT_FOUND'))
+
+ def do_POST(self):
+ if self.path != '/setup/connect':
+ return self.reply(404, dict(error='NOT_FOUND'))
+ try:
+ length = int(self.headers.get('Content-Length') or 0)
+ body = json.loads(self.rfile.read(min(length, 16384)) or b'{}')
+ except ValueError:
+ return self.reply(400, dict(error='BAD_REQUEST', message='Send a JSON object.'))
+ problem = check_request(body)
+ if problem:
+ return self.reply(400, dict(error='BAD_REQUEST', message=problem))
+ if not setup.requests.empty():
+ return self.reply(409, dict(error='BUSY', message='Already joining a Wi-Fi.'))
+ self.reply(202, dict(state='connecting', run=setup.run + 1))
+ setup.requests.put(body)
+
+ return Handler
+
+
+def serve(setup):
+ server = http.server.ThreadingHTTPServer((ADDRESS, PORT), setup.handler())
+ server.daemon_threads = True
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
+def saved_comes_back(device):
+ """Off the hotspot for a moment, each saved Wi-Fi tried in turn. `device connect` cannot do it:
+ with no access point named, NetworkManager refuses ("A 'wireless' setting is required")."""
+ # A device someone disconnected is barred from joining by itself until allowed again.
+ nmcli('device', 'set', device, 'autoconnect', 'yes')
+ for row in rows('-f', 'UUID,TYPE,NAME', 'connection', 'show'):
+ if len(row) != 3 or row[1] != '802-11-wireless' or row[2] == HOTSPOT:
+ continue
+ try:
+ nmcli('connection', 'up', 'uuid', row[0], 'ifname', device, wait=SAVED_JOIN)
+ except subprocess.TimeoutExpired:
+ pass
+ if online():
+ return True
+ return False
+
+
+def setup_mode(device, asked=False):
+ """Hotspot until the phone sends a Wi-Fi that works, or saved Wi-Fi comes back.
+
+ Saved Wi-Fi is tried again only for a computer signed in that lost its network (a router that
+ was off). One not signed in still needs the phone, and one [asked] for setup by hand was taken
+ off its Wi-Fi on purpose: both keep the hotspot until somebody uses it."""
+ may_leave = not asked and signed_in()
+ name = hotspot_name()
+ networks = visible_networks(name)
+ try:
+ while True:
+ if not start_hotspot(device, name):
+ return False
+ # The screen's Wi-Fi page lists these while the radio hosts the hotspot (network.py).
+ show_networks(networks, device)
+ run = int(read_result().get('run') or 0)
+ log(f'hotspot "{name}" is up with {len(networks)} networks to offer')
+ setup = Setup(name, networks, run)
+ try:
+ server = serve(setup)
+ except OSError as error:
+ log(f'could not answer on {ADDRESS}:{PORT}: {error}')
+ stop_hotspot()
+ return False
+ request, idle_since, elsewhere = None, time.monotonic(), None
+ while request is None:
+ try:
+ request = setup.requests.get(timeout=5)
+ except queue.Empty:
+ # Someone at the screen took the radio for a Wi-Fi (network.py): joined, or not.
+ if not hotspot_up():
+ elsewhere = online()
+ break
+ if phones_on(device):
+ idle_since = time.monotonic()
+ elif may_leave and time.monotonic() - idle_since >= RETRY_SAVED and saved_wifi():
+ break
+ if request is not None:
+ run += 1
+ write_result(state='connecting', ssid=request['ssid'], run=run)
+ # Let the phone read its answer before the hotspot goes.
+ time.sleep(2)
+ server.shutdown()
+ server.server_close()
+ stop_hotspot()
+ if elsewhere is not None:
+ if elsewhere or wait_online(SAVED_JOIN):
+ log('joined a Wi-Fi from the screen')
+ return True
+ # Their Wi-Fi failed: the hotspot comes back for the phone.
+ continue
+ if request is None:
+ log('nobody is on the hotspot; trying saved Wi-Fi')
+ if saved_comes_back(device):
+ log('saved Wi-Fi is back')
+ return True
+ networks = visible_networks(name) or networks
+ continue
+ result = join(request, networks, device)
+ write_result(run=run, **result)
+ if result['state'] == 'done':
+ return True
+ # Back to the hotspot with the reason; the list may have changed meanwhile.
+ networks = visible_networks(name) or networks
+ finally:
+ SCREEN_NETWORKS.unlink(missing_ok=True)
+
+
+def hotspot_up():
+ return any(len(row) == 1 and row[0] == HOTSPOT for row in rows('-f', 'NAME', 'connection', 'show', '--active'))
+
+
+def wait_online(seconds):
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ if online():
+ return True
+ time.sleep(3)
+ return online()
+
+
+def show_networks(networks, device):
+ """For the screen's Wi-Fi page (network.py), which cannot scan while the radio hosts the hotspot."""
+ try:
+ SCREEN_NETWORKS.parent.mkdir(parents=True, exist_ok=True)
+ SCREEN_NETWORKS.write_text(json.dumps([dict(row, device=device) for row in networks]))
+ except OSError:
+ pass
+
+
+def asked_now():
+ try:
+ NOW.unlink()
+ return True
+ except OSError:
+ return False
+
+
+def headless():
+ """No screen to set Wi-Fi on: marked so (a device, or a laptop standing in for one), or no
+ display connected. A computer with a screen keeps its own Wi-Fi page and never loses its radio
+ to the hotspot unless someone asks (`setup.py now`)."""
+ if HEADLESS.exists():
+ return True
+ return not any(status.read_text().strip() == 'connected'
+ for status in DRM.glob('card*-*/status') if status.is_file())
+
+
+def watch():
+ started, offline_since = time.monotonic(), None
+ while True:
+ now = time.monotonic()
+ forced = asked_now()
+ if (online() or not headless()) and not forced:
+ offline_since = None
+ else:
+ offline_since = offline_since or now
+ wait = OFFLINE_AT_START if now - started < OFFLINE_AT_START + 5 else OFFLINE_LATER
+ device = wifi_device()
+ if device and (forced or now - offline_since >= wait):
+ if forced:
+ # Asked for by hand: leave the current Wi-Fi so the radio can host the hotspot.
+ nmcli('device', 'disconnect', device)
+ setup_mode(device, asked=forced)
+ offline_since = None
+ time.sleep(5)
+
+
+def active_wifi(device):
+ """The saved profile this computer is on now, to come back to when a new Wi-Fi fails."""
+ for row in rows('-f', 'UUID,TYPE,DEVICE', 'connection', 'show', '--active'):
+ if len(row) == 3 and row[1] == '802-11-wireless' and row[2] == device:
+ return row[0]
+ return None
+
+
+def change(request):
+ """The phone asked, through the daemon while online (`os_device` `wifi_join`), for another Wi-Fi.
+ Joined like setup's, but a failure goes back to the Wi-Fi it was on, so a wrong password from far
+ away does not leave the computer off the network. The result is kept for the phone to read once
+ the computer is back (`wifi_result`)."""
+ problem = check_request(request)
+ run = int(read_result().get('run') or 0) + 1
+ if problem:
+ write_result(run=run, state='failed', error='BAD_REQUEST', message=problem)
+ return
+ device = wifi_device()
+ if not device:
+ write_result(run=run, state='failed', error='WIFI', message='This computer has no Wi-Fi.')
+ return
+ ssid = request['ssid']
+ write_result(run=run, state='connecting', ssid=ssid)
+ before = active_wifi(device)
+ networks = visible_networks(hotspot_name())
+ result = join(dict(ssid=ssid, password=request.get('password') or ''), networks, device)
+ if result['state'] != 'done' and before:
+ # Back where it was: the phone reaches it again there and reads why.
+ try:
+ nmcli('connection', 'up', 'uuid', before, 'ifname', device, wait=SAVED_JOIN)
+ except subprocess.TimeoutExpired:
+ pass
+ result['restored'] = online()
+ write_result(run=run, **result)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument('command', nargs='?', choices=['watch', 'now', 'name', 'join'], default='watch')
+ arguments = parser.parse_args()
+ if arguments.command == 'join':
+ # From the daemon, through sudo: the Wi-Fi as JSON on stdin, never in argv.
+ try:
+ request = json.loads(sys.stdin.read(16384) or '{}')
+ except ValueError:
+ request = None
+ change(request)
+ return
+ if arguments.command == 'now':
+ # For a person at the computer, or a test: leave the current Wi-Fi for the hotspot now.
+ NOW.parent.mkdir(parents=True, exist_ok=True)
+ NOW.touch()
+ return
+ if arguments.command == 'name':
+ print(hotspot_name())
+ return
+ log(f'watching; hotspot "{hotspot_name()}" when there is no network')
+ watch()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/test_network.py b/os/tests/test_network.py
index a0a9a22f4..f59438ff0 100644
--- a/os/tests/test_network.py
+++ b/os/tests/test_network.py
@@ -35,6 +35,12 @@ class Screen:
class Network(unittest.TestCase):
+ def setUp(self):
+ # No setup hotspot unless a test says so (SetupHotspot below): its own nmcli call stays out of
+ # the counted ones.
+ hotspot = patch.object(network, 'setup_hotspot_up', return_value=False)
+ hotspot.start()
+ self.addCleanup(hotspot.stop)
def test_privileged_form_uses_a_fixed_executable_not_the_callers_path(self):
with patch.object(network.subprocess, 'run', return_value=result()) as run:
network.nmcli('general')
@@ -270,3 +276,50 @@ class Network(unittest.TestCase):
def test_wide_and_control_characters_fit_the_terminal(self):
self.assertEqual(network.fit('網路123', 5), '網路1')
self.assertEqual(network.fit('a\x1b\tb', 6), 'a b ')
+
+
+class SetupHotspot(unittest.TestCase):
+ """While setup.py hosts its hotspot for a phone, the page looks as it always does."""
+
+ def test_the_hotspot_is_seen_among_the_active_connections(self):
+ with patch.object(network, 'nmcli', return_value=result(output='harness-setup\nlo\n')):
+ self.assertTrue(network.setup_hotspot_up())
+ with patch.object(network, 'nmcli', return_value=result(output='Glinks 1\n')):
+ self.assertFalse(network.setup_hotspot_up())
+
+ def test_the_list_is_the_one_seen_before_the_hotspot_not_the_hotspot(self):
+ import tempfile
+ with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as handle:
+ handle.write('[{"ssid": "Weak", "signal": 30, "security": "WPA2", "device": "wlo1"},'
+ ' {"ssid": "Glinks 1", "signal": 80, "security": "WPA2", "device": "wlo1"},'
+ ' {"ssid": "Cafe", "signal": 50, "security": "", "device": "wlo1"}, {"bad": 1}]')
+ self.addCleanup(Path(handle.name).unlink)
+ with patch.object(network, 'SETUP_NETWORKS', handle.name), \
+ patch.object(network, 'setup_hotspot_up', return_value=True), \
+ patch.object(network, 'nmcli') as command:
+ rows = network.scan(rescan=True)
+ command.assert_not_called()
+ self.assertEqual([row['ssid'] for row in rows], ['Glinks 1', 'Cafe', 'Weak'])
+ self.assertEqual(rows[1]['security'], '--')
+ self.assertFalse(any(row['active'] for row in rows))
+
+ def test_no_list_is_an_empty_one(self):
+ with patch.object(network, 'SETUP_NETWORKS', '/nonexistent/setup-networks.json'):
+ self.assertEqual(network.setup_networks(), [])
+
+ def test_the_hotspot_alone_is_not_online(self):
+ with patch.object(network, 'nmcli', return_value=result(output='connected (local only)')), \
+ patch.object(network, 'setup_hotspot_up', return_value=True), \
+ patch.object(network, 'wired_devices', return_value=[]):
+ self.assertFalse(network.connected())
+ with patch.object(network, 'nmcli', return_value=result(output='connected')), \
+ patch.object(network, 'setup_hotspot_up', return_value=True), \
+ patch.object(network, 'wired_devices', return_value=[['ens5', 'ethernet', 'connected']]):
+ self.assertTrue(network.connected())
+
+ def test_choosing_a_network_on_screen_takes_the_radio_back_first(self):
+ calls = []
+ with patch.object(network, 'setup_hotspot_up', return_value=True), \
+ patch.object(network, 'nmcli', side_effect=lambda *a, secret=None, wait=8: calls.append(a) or result()):
+ self.assertTrue(network.connect(WIFI, 'password1'))
+ self.assertEqual(calls[0], ('connection', 'down', 'id', 'harness-setup'))
diff --git a/os/tests/test_setup.py b/os/tests/test_setup.py
new file mode 100644
index 000000000..c8d628630
--- /dev/null
+++ b/os/tests/test_setup.py
@@ -0,0 +1,292 @@
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('setup', Path(__file__).resolve().parents[1] / 'setup.py')
+setup = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(setup)
+
+
+def result(code=0, output='', error=''):
+ return subprocess.CompletedProcess([], code, output, error)
+
+
+class Requests(unittest.TestCase):
+ def test_a_wifi_and_ticket_pass(self):
+ self.assertIsNone(setup.check_request(dict(ssid='Glink 1', password='@11235813', ticket='t')))
+ self.assertIsNone(setup.check_request(dict(ssid='Cafe')))
+ self.assertIsNone(setup.check_request(dict(ssid='Cafe', password='')))
+
+ def test_what_a_wifi_cannot_take_is_refused_before_leaving_the_hotspot(self):
+ self.assertEqual(setup.check_request([]), 'Send a JSON object.')
+ self.assertEqual(setup.check_request(dict(ssid='')), 'Choose a Wi-Fi network.')
+ self.assertEqual(setup.check_request(dict(ssid='x' * 33)), 'Choose a Wi-Fi network.')
+ self.assertEqual(setup.check_request(dict(ssid='a', password='short')), 'A Wi-Fi password has 8 to 63 characters.')
+ self.assertEqual(setup.check_request(dict(ssid='a', password='x' * 64)), 'A Wi-Fi password has 8 to 63 characters.')
+ self.assertEqual(setup.check_request(dict(ssid='a', password='two\nlines')), 'That Wi-Fi password cannot be used.')
+ self.assertEqual(setup.check_request(dict(ssid='a', ticket='bad\x00')), 'That sign-in ticket cannot be used.')
+
+
+class Reasons(unittest.TestCase):
+ def test_network_manager_failures_become_what_the_person_can_fix(self):
+ cases = {
+ 'Error: Connection activation failed: Secrets were required, but not provided.': 'WRONG_PASSWORD',
+ 'Error: Connection activation failed: (7) no-secrets': 'WRONG_PASSWORD',
+ 'Error: Connection activation failed: The Wi-Fi network could not be found': 'NOT_FOUND',
+ 'Error: No network with SSID \'x\' found.': 'NOT_FOUND',
+ 'Error: Connection activation failed: IP configuration could not be reserved': 'NO_ADDRESS',
+ 'Error: Timeout expired (45 seconds)': 'TIMEOUT',
+ 'Error: something else': 'WIFI',
+ }
+ for output, expected in cases.items():
+ self.assertEqual(setup.reason(output), expected, output)
+
+
+class Connect(unittest.TestCase):
+ def test_the_password_goes_through_stdin_and_an_older_profile_for_the_wifi_goes(self):
+ calls = []
+
+ def nmcli(*args, secret=None, wait=8):
+ calls.append((args, secret))
+ if args[:2] == ('-t', '-e'):
+ return result(output='old-uuid:802-11-wireless\n')
+ if args[:2] == ('-g', '802-11-wireless.ssid'):
+ return result(output='Glink 1\n')
+ return result()
+
+ with patch.object(setup, 'nmcli', side_effect=nmcli):
+ self.assertIsNone(setup.connect('Glink 1', '@11235813', 'WPA2', 'wlo1'))
+ flat = [' '.join(args) for args, _ in calls]
+ self.assertFalse(any('@11235813' in line for line in flat))
+ up = next((args, secret) for args, secret in calls if args[:2] == ('connection', 'up'))
+ self.assertEqual(up[1], '802-11-wireless-security.psk:@11235813\n')
+ self.assertIn('connection delete uuid old-uuid', flat)
+
+ def test_a_failed_join_leaves_no_profile_and_says_why(self):
+ calls = []
+
+ def nmcli(*args, secret=None, wait=8):
+ calls.append(args)
+ if args[:2] == ('connection', 'up'):
+ return result(4, error='Error: Connection activation failed: Secrets were required, but not provided.')
+ return result()
+
+ with patch.object(setup, 'nmcli', side_effect=nmcli):
+ self.assertEqual(setup.connect('Glink 1', 'wrongpass', 'WPA2', 'wlo1'), 'WRONG_PASSWORD')
+ self.assertEqual(calls[-1][:2], ('connection', 'delete'))
+
+ def test_a_refused_key_ends_the_join_early_as_a_wrong_password(self):
+ # NetworkManager keeps retrying a wrong key until its wait runs out; wpa_supplicant says so.
+ released = []
+
+ def nmcli(*args, secret=None, wait=8):
+ if args[:2] == ('connection', 'up'):
+ for _ in range(100):
+ if released:
+ return result(4, error='Error: Connection activation failed')
+ time.sleep(.01)
+ raise subprocess.TimeoutExpired('nmcli', wait)
+ if args[:2] == ('connection', 'down'):
+ released.append(True)
+ return result()
+
+ with patch.object(setup, 'nmcli', side_effect=nmcli), \
+ patch.object(setup, 'wrong_keys', return_value=2):
+ self.assertEqual(setup.connect('Glinks 1', 'wrongpass', 'WPA2', 'wlo1'), 'WRONG_PASSWORD')
+ self.assertTrue(released)
+
+ def test_a_join_that_hangs_is_a_timeout(self):
+ def nmcli(*args, secret=None, wait=8):
+ if args[:2] == ('connection', 'up'):
+ raise subprocess.TimeoutExpired('nmcli', wait)
+ return result()
+
+ with patch.object(setup, 'nmcli', side_effect=nmcli):
+ self.assertEqual(setup.connect('Far', 'password1', 'WPA2', 'wlo1'), 'TIMEOUT')
+
+ def test_an_open_network_sends_no_secret(self):
+ seen = []
+ with patch.object(setup, 'nmcli', side_effect=lambda *a, secret=None, wait=8: seen.append((a, secret)) or result()):
+ setup.connect('Cafe', '', '', 'wlo1')
+ self.assertTrue(all(secret is None for _, secret in seen))
+ self.assertFalse(any('wifi-sec.key-mgmt' in args for args, _ in seen))
+
+
+class Join(unittest.TestCase):
+ NETWORKS = [dict(ssid='Glink 1', signal=80, security='WPA2')]
+
+ def test_wifi_internet_and_ticket_sign_the_computer_in(self):
+ with patch.object(setup, 'connect', return_value=None) as connect, \
+ patch.object(setup, 'internet', return_value=True), \
+ patch.object(setup, 'sign_in', return_value=(True, '')) as sign_in, \
+ patch.object(setup, 'signed_in', return_value=True):
+ out = setup.join(dict(ssid='Glink 1', password='@11235813', ticket='t'), self.NETWORKS, 'wlo1')
+ self.assertEqual(out, dict(state='done', ssid='Glink 1', signedIn=True))
+ connect.assert_called_once_with('Glink 1', '@11235813', 'WPA2', 'wlo1')
+ sign_in.assert_called_once_with('t')
+
+ def test_wifi_without_internet_is_forgotten_and_reported(self):
+ with patch.object(setup, 'connect', return_value=None), \
+ patch.object(setup, 'internet', return_value=False), \
+ patch.object(setup, 'forget') as forget:
+ out = setup.join(dict(ssid='Hotel', password='password1'), self.NETWORKS, 'wlo1')
+ forget.assert_called_once_with('Hotel')
+ self.assertEqual(out['error'], 'NO_INTERNET')
+ self.assertIn('"Hotel"', out['message'])
+
+ def test_a_wrong_password_comes_back_with_its_message(self):
+ with patch.object(setup, 'connect', return_value='WRONG_PASSWORD'):
+ out = setup.join(dict(ssid='Glink 1', password='wrongpass'), self.NETWORKS, 'wlo1')
+ self.assertEqual(out, dict(state='failed', error='WRONG_PASSWORD', ssid='Glink 1',
+ message='The password for "Glink 1" is not right. Passwords are case-sensitive.'))
+
+ def test_a_hidden_network_is_protected_when_a_password_is_given(self):
+ with patch.object(setup, 'connect', return_value='NOT_FOUND') as connect:
+ setup.join(dict(ssid='Hidden', password='password1'), self.NETWORKS, 'wlo1')
+ connect.assert_called_once_with('Hidden', 'password1', 'WPA2', 'wlo1')
+
+ def test_a_refused_ticket_still_keeps_the_wifi(self):
+ with patch.object(setup, 'connect', return_value=None), \
+ patch.object(setup, 'internet', return_value=True), \
+ patch.object(setup, 'sign_in', return_value=(False, 'This ticket was already used or has expired.')):
+ out = setup.join(dict(ssid='Glink 1', password='@11235813', ticket='t'), self.NETWORKS, 'wlo1')
+ self.assertEqual(out['state'], 'done')
+ self.assertEqual(out['error'], 'SIGN_IN')
+
+
+class Change(unittest.TestCase):
+ def setUp(self):
+ self.folder = tempfile.TemporaryDirectory()
+ state = Path(self.folder.name)
+ self.patches = [patch.object(setup, 'STATE', state), patch.object(setup, 'RESULT', state / 'r.json'),
+ patch.object(setup, 'wifi_device', return_value='wlo1'),
+ patch.object(setup, 'active_wifi', return_value='u-home'),
+ patch.object(setup, 'visible_networks', return_value=[dict(ssid='Cafe', signal=70, security='WPA2')])]
+ for one in self.patches:
+ one.start()
+
+ def tearDown(self):
+ for one in self.patches:
+ one.stop()
+ self.folder.cleanup()
+
+ def test_a_failed_wifi_goes_back_to_the_one_it_was_on(self):
+ with patch.object(setup, 'join', return_value=dict(state='failed', error='WRONG_PASSWORD', ssid='Cafe',
+ message='m')), \
+ patch.object(setup, 'nmcli', return_value=result()) as nmcli, \
+ patch.object(setup, 'online', return_value=True):
+ setup.change(dict(ssid='Cafe', password='wrongpass'))
+ nmcli.assert_called_once_with('connection', 'up', 'uuid', 'u-home', 'ifname', 'wlo1', wait=setup.SAVED_JOIN)
+ out = setup.read_result()
+ self.assertEqual((out['state'], out['error'], out['restored'], out['run']), ('failed', 'WRONG_PASSWORD', True, 1))
+
+ def test_a_working_wifi_stays(self):
+ with patch.object(setup, 'join', return_value=dict(state='done', ssid='Cafe', signedIn=True)), \
+ patch.object(setup, 'nmcli') as nmcli:
+ setup.change(dict(ssid='Cafe', password='password1'))
+ nmcli.assert_not_called()
+ self.assertEqual(setup.read_result()['state'], 'done')
+
+ def test_a_bad_request_changes_nothing(self):
+ with patch.object(setup, 'join') as join:
+ setup.change(dict(ssid='', password='x'))
+ setup.change(None)
+ join.assert_not_called()
+ self.assertEqual(setup.read_result()['error'], 'BAD_REQUEST')
+
+
+class Screen(unittest.TestCase):
+ def test_a_wifi_chosen_on_the_screen_ends_setup_and_its_list_goes(self):
+ class Server:
+ def shutdown(self): pass
+ def server_close(self): pass
+
+ with tempfile.TemporaryDirectory() as folder:
+ listed = Path(folder) / 'setup-networks.json'
+ seen = []
+ with patch.object(setup, 'SCREEN_NETWORKS', listed), \
+ patch.object(setup, 'visible_networks', return_value=[dict(ssid='Glinks 1', signal=80, security='WPA2')]), \
+ patch.object(setup, 'start_hotspot', return_value=True), \
+ patch.object(setup, 'serve', return_value=Server()), \
+ patch.object(setup, 'read_result', return_value={}), \
+ patch.object(setup, 'signed_in', return_value=False), \
+ patch.object(setup, 'stop_hotspot'), \
+ patch.object(setup, 'hotspot_up', side_effect=lambda: seen.append(json.loads(listed.read_text())) or False), \
+ patch.object(setup, 'online', return_value=True), \
+ patch.object(setup.queue.Queue, 'get', side_effect=setup.queue.Empty):
+ self.assertTrue(setup.setup_mode('wlo1'))
+ self.assertEqual(seen[0], [dict(ssid='Glinks 1', signal=80, security='WPA2', device='wlo1')])
+ self.assertFalse(listed.exists())
+
+
+class Machine(unittest.TestCase):
+ def test_online_ignores_the_setup_hotspot(self):
+ with patch.object(setup, 'nmcli', return_value=result(output='harness-setup:802-11-wireless\nlo:loopback\n')):
+ self.assertFalse(setup.online())
+ with patch.object(setup, 'nmcli', return_value=result(output='Glink 1:802-11-wireless\n')):
+ self.assertTrue(setup.online())
+ with patch.object(setup, 'nmcli', return_value=result(output='Wired:802-3-ethernet\n')):
+ self.assertTrue(setup.online())
+
+ def test_saved_wifi_is_brought_up_by_name_not_by_device(self):
+ calls = []
+
+ def nmcli(*args, secret=None, wait=8):
+ calls.append(args)
+ if args[-2:] == ('connection', 'show'):
+ return result(output='u-hot:802-11-wireless:harness-setup\nu-home:802-11-wireless:Glinks 1\nu-lo:loopback:lo\n')
+ return result()
+
+ with patch.object(setup, 'nmcli', side_effect=nmcli), patch.object(setup, 'online', return_value=True):
+ self.assertTrue(setup.saved_comes_back('wlo1'))
+ self.assertIn(('device', 'set', 'wlo1', 'autoconnect', 'yes'), calls)
+ self.assertIn(('connection', 'up', 'uuid', 'u-home', 'ifname', 'wlo1'), calls)
+ self.assertFalse(any('u-hot' in args for args in calls))
+ self.assertFalse(any(args[:2] == ('device', 'connect') for args in calls))
+
+ def test_the_hotspot_is_named_after_the_computer(self):
+ with tempfile.TemporaryDirectory() as folder:
+ state = Path(folder)
+ with patch.object(setup, 'COMPUTER_ID', state / 'computer-id'):
+ (state / 'computer-id').write_text('601cb0af-9a2d-44cf-8381-df989bf4a192\n')
+ self.assertEqual(setup.hotspot_name(), 'Harness-A192')
+
+ def test_the_hotspot_is_open_on_2_4_ghz(self):
+ calls = []
+ with patch.object(setup, 'nmcli', side_effect=lambda *a, secret=None, wait=8: calls.append((a, secret)) or result()):
+ self.assertTrue(setup.start_hotspot('wlo1', 'Harness-A192'))
+ add = next(args for args, _ in calls if args[:2] == ('connection', 'add'))
+ self.assertIn('ap', add)
+ self.assertIn('bg', add)
+ self.assertFalse(any('wifi-sec.key-mgmt' in args for args, _ in calls))
+
+ def test_only_a_computer_without_a_screen_is_headless(self):
+ with tempfile.TemporaryDirectory() as folder:
+ root = Path(folder)
+ (root / 'card1-eDP-1').mkdir()
+ (root / 'card1-eDP-1/status').write_text('connected\n')
+ (root / 'card1-HDMI-A-1').mkdir()
+ (root / 'card1-HDMI-A-1/status').write_text('disconnected\n')
+ with patch.object(setup, 'DRM', root), patch.object(setup, 'HEADLESS', root / 'headless'):
+ self.assertFalse(setup.headless())
+ (root / 'headless').touch()
+ self.assertTrue(setup.headless())
+ (root / 'headless').unlink()
+ (root / 'card1-eDP-1/status').write_text('disconnected\n')
+ self.assertTrue(setup.headless())
+
+ def test_results_carry_the_run_for_the_phone(self):
+ with tempfile.TemporaryDirectory() as folder:
+ with patch.object(setup, 'STATE', Path(folder)), patch.object(setup, 'RESULT', Path(folder) / 'r.json'):
+ setup.write_result(state='failed', run=3, error='WRONG_PASSWORD')
+ self.assertEqual(setup.read_result()['run'], 3)
+ self.assertEqual(json.loads((Path(folder) / 'r.json').read_text())['error'], 'WRONG_PASSWORD')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tools/build-package.py b/os/tools/build-package.py
index d61aba5c2..c8b1936d7 100644
--- a/os/tools/build-package.py
+++ b/os/tools/build-package.py
@@ -13,7 +13,8 @@ import tarfile
import tempfile
-DEPENDENCIES = ('nodejs-lts-jod', 'tmux', 'foot', 'gtklock', 'grim', 'slurp')
+# dnsmasq: NetworkManager's shared mode hands the setup hotspot's phone an address with it.
+DEPENDENCIES = ('nodejs-lts-jod', 'tmux', 'foot', 'gtklock', 'grim', 'slurp', 'dnsmasq')
def package_info(version, timestamp, size, compositor_dependencies=()):
@@ -63,6 +64,7 @@ def stage(source, runtime, destination, commit):
'os/installer.py': 'usr/lib/harness-os/install.py',
'os/onboarding.py': 'usr/lib/harness-os/onboarding.py',
'os/network.py': 'usr/lib/harness-os/network.py',
+ 'os/setup.py': 'usr/lib/harness-os/setup.py',
'os/projects.py': 'usr/lib/harness-os/projects.py',
'os/trial_projects.py': 'usr/lib/harness-os/trial_projects.py',
'os/system.py': 'usr/lib/harness-os/system.py',