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.

Harness OS: a phone sees each part's version, updates with the restart, and unlocks a computer updated from 0.1.6 (#1498)

Bubu-Dudu-52hzce706e34f28b
diff --git a/cli/src/services/osDevice.spec.ts b/cli/src/services/osDevice.spec.ts
index 7d7a15e8d..1fa405d3c 100644
--- a/cli/src/services/osDevice.spec.ts
+++ b/cli/src/services/osDevice.spec.ts
@@ -3,7 +3,7 @@ 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,
+ activeSsid, CMDLINE, 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'
@@ -19,13 +19,14 @@ const STATUS = JSON.stringify({
function service(over: OsDeviceDeps = {}) {
const exec = vi.fn(async (file: string, args: readonly string[]) => {
- if (file === '/usr/bin/python3') return STATUS
+ if (file === '/usr/bin/python3') return args[0] === SETUP ? 'Harness-BD19\n' : 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 readFile = async (path: string) => path === CMDLINE ? 'BOOT_IMAGE=/vmlinuz rd.luks.name=abc=cryptroot quiet\n' : '{"ok":true,"ssid":"Cafe"}'
+ const deps: OsDeviceDeps = { env: {}, exists: () => true, exec, spawnDetached, now: () => clock, readFile, ...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 } }
}
@@ -64,17 +65,31 @@ describe('the Harness OS computer, managed from the phone', () => {
expect(exists).toHaveBeenCalledWith(LIVE_UPDATE)
})
- it('reads the update and the network the computer is on, bounded', async () => {
+ it('reads the update, the network the computer is on, its hotspot and whether it is encrypted, 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(await ask({ action: 'status' })).toEqual({
+ harnessOs: true,
+ update: {
+ available: true, runtime: '0.9.1', version: 'bbb',
+ parts: {
+ os: { running: null, available: false, next: null },
+ hn: { running: '1.2.3', available: true, next: null },
+ cli: { running: '0.9.1', available: true, next: null },
+ },
+ },
+ wifi: { ssid: 'Home: 5G' }, hotspot: 'Harness-BD19', encrypted: true,
+ })
expect(exec).toHaveBeenCalledWith('/usr/bin/python3', [LIVE_UPDATE, 'status'], { timeout: 15_000 })
+ expect(exec).toHaveBeenCalledWith('/usr/bin/python3', [SETUP, 'name'], { timeout: 10_000 })
expect(exec).toHaveBeenCalledWith('nmcli', ['-t', '-e', 'yes', '-f', 'ACTIVE,SSID', 'device', 'wifi'], { timeout: 10_000 })
+ const plain = service({ readFile: async (path: string) => path === CMDLINE ? 'BOOT_IMAGE=/vmlinuz root=UUID=x quiet\n' : '{}' })
+ expect(await plain.ask({ action: 'status' })).toMatchObject({ encrypted: false })
})
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 } })
+ expect(await failing(new Error('Command failed: python3\nTraceback ...'))).toEqual({ harnessOs: true, update: { available: false, error: 'Command failed: python3' }, wifi: { ssid: null }, hotspot: null, encrypted: true })
+ expect(await failing('killed')).toEqual({ harnessOs: true, update: { available: false, error: 'killed' }, wifi: { ssid: null }, hotspot: null, encrypted: true })
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]') })
@@ -83,11 +98,33 @@ describe('the Harness OS computer, managed from the phone', () => {
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' })
+ .toMatchObject({ 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 })
+ .toMatchObject({ available: false, runtime: 'aaa', restartRequired: true })
+ expect(updateOf({ runtime: '/b/aaa', ready: '/b/ccc', system: { available: true } })).toMatchObject({ available: true, runtime: 'aaa', version: 'ccc' })
+ expect(updateOf({ system: [], versions: [] })).toMatchObject({ available: false, runtime: null })
+ })
+
+ it('names each part, what runs and what waits: the OS alone, hn and the CLI as one runtime', () => {
+ expect(updateOf({
+ runtime: '/b/aaa', ready: '/b/ccc', os: '0.1.7.r1-1', versions: { hn: '0.1.38', cli: '0.4.29' },
+ ready_versions: { hn: '0.1.39', cli: '0.4.30' }, system: { available: true, version: '0.1.8.r2-1' },
+ }).parts).toEqual({
+ os: { running: '0.1.7.r1-1', available: true, next: '0.1.8.r2-1' },
+ hn: { running: '0.1.38', available: true, next: '0.1.39' },
+ cli: { running: '0.4.29', available: true, next: '0.4.30' },
+ })
+ expect(updateOf({ runtime: '/b/aaa', ready: '/b/aaa', os: '0.1.7.r1-1', versions: { hn: '0.1.38', cli: '0.4.29' }, system: {} }).parts).toEqual({
+ os: { running: '0.1.7.r1-1', available: false, next: null },
+ hn: { running: '0.1.38', available: false, next: null },
+ cli: { running: '0.4.29', available: false, next: null },
+ })
+ })
+
+ it('starts a phone\'s update with the restart it agreed to', async () => {
+ const { ask, spawnDetached } = service()
+ expect(await ask({ action: 'update', reboot: true })).toEqual({ started: true })
+ expect(spawnDetached).toHaveBeenCalledWith('/usr/bin/harness', ['update', '--reboot'])
})
it('starts the update detached, once in ten minutes', async () => {
diff --git a/cli/src/services/osDevice.ts b/cli/src/services/osDevice.ts
index eaccca26b..65ba2bae5 100644
--- a/cli/src/services/osDevice.ts
+++ b/cli/src/services/osDevice.ts
@@ -25,6 +25,7 @@ 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 CMDLINE = '/proc/cmdline'
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. */
@@ -127,6 +128,15 @@ export function updateOf(status: Payload): Payload {
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
+ // Each part on its own, for the phone's Version page: what runs, and what is waiting. hn and the CLI come
+ // as one runtime; the OS package alone needs the computer restarted.
+ const text = (value: unknown): string | null => typeof value === 'string' && value ? value : null
+ const waiting = record(status.ready_versions) ? status.ready_versions : {}
+ update.parts = {
+ os: { running: text(status.os), available: system.available === true, next: system.available === true ? text(system.version) : null },
+ hn: { running: text(versions.hn), available: runtimeReady, next: runtimeReady ? text(waiting.hn) : null },
+ cli: { running: text(versions.cli), available: runtimeReady, next: runtimeReady ? text(waiting.cli) : null },
+ }
return update
}
@@ -159,20 +169,27 @@ export function startOsDevice(_core: CoreApi, deps: OsDeviceDeps = {}): ServiceR
const status = async (): Promise<Payload> => {
if (!harnessOs()) return { harnessOs: false }
- const [update, ssid] = await Promise.all([
+ const [update, ssid, hotspot, cmdline] = 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(),
+ // The open Wi-Fi it hosts while locked or not set up: where a phone finds it after a restart.
+ exec(PYTHON, [SETUP, 'name'], { timeout: NMCLI_TIMEOUT_MS }).then((out) => out.trim() || null).catch(() => null),
+ read(CMDLINE).catch(() => ''),
])
- return { harnessOs: true, update, wifi: { ssid } }
+ // Encrypted, it waits for its password at every start (installer.py: rd.luks.name=).
+ return { harnessOs: true, update, wifi: { ssid }, hotspot, encrypted: /(^|\s)rd\.luks\.name=/.test(cmdline) }
}
- const update = (): Payload => {
+ const update = (payload: Payload): Payload => {
if (updateStartedAt !== null && now() - updateStartedAt < UPDATE_BUSY_MS) return { error: 'BUSY' }
- detached(HARNESS, ['update'])
+ // From a phone the person agreed to the restart there: a system update restarts the computer at once.
+ const args = payload.reboot === true ? ['update', '--reboot'] : ['update']
+ console.log(`[os-device] harness ${args.join(' ')}`)
+ detached(HARNESS, args)
updateStartedAt = now()
return { started: true }
}
@@ -206,7 +223,7 @@ export function startOsDevice(_core: CoreApi, deps: OsDeviceDeps = {}): ServiceR
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 === 'update') return update(payload)
if (action === 'wifi_scan') return await scan()
if (action === 'wifi_join') return join(payload)
return await result()
diff --git a/os/live_update.py b/os/live_update.py
index 91baa6c2f..7462ffd77 100644
--- a/os/live_update.py
+++ b/os/live_update.py
@@ -887,7 +887,11 @@ def main(argv=None):
parser.add_argument('action', choices=['check', 'screen', 'request', 'apply', 'rollback', 'status', 'update'], nargs='?', default='screen')
parser.add_argument('--feeds', type=Path, help='Explicit developer feed map; never used by the installed timer')
parser.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
+ parser.add_argument('--reboot', action='store_true',
+ help='With update: restart at once when the system needs it (asked from a phone)')
args = parser.parse_args(argv)
+ if args.reboot and args.action != 'update':
+ parser.error('--reboot is only valid for update')
if args.worker and args.action != 'apply':
parser.error('--worker is only valid for apply')
if os.geteuid() == 0 or Path('/etc/harness-live').exists():
@@ -910,7 +914,7 @@ def main(argv=None):
check(read(args.feeds) if args.feeds else None)
finish_approved_update()
elif args.action == 'update':
- return update_from_terminal(read(args.feeds) if args.feeds else None)
+ return update_from_terminal(read(args.feeds) if args.feeds else None, reboot=args.reboot)
elif args.action == 'screen':
with screen_registration():
run_screen()
@@ -923,8 +927,11 @@ def main(argv=None):
print(WORKER_BUSY, flush=True)
return BUSY_EXIT
else:
- print(json.dumps({'runtime': str(selected()), 'versions': versions(selected()),
- 'ready': str(prepared()) if prepared() else None,
+ ready = prepared()
+ print(json.dumps({'runtime': str(selected()), 'versions': versions(selected()), 'os': os_version(),
+ 'ready': str(ready) if ready else None,
+ # What the prepared runtime carries, for a phone to name before it updates.
+ 'ready_versions': versions(ready) if ready and ready != selected() else None,
'restart_required': RESTART_REQUIRED.exists(),
'system': system_channel(), 'check': read(STATE / 'check.json')}, indent=2))
@@ -939,13 +946,33 @@ def daemon_version():
return version if isinstance(version, str) and version else None
-def update_from_terminal(feeds=None):
+def os_version():
+ """The Harness OS package installed, as pacman names it; None where there is none."""
+ try:
+ name, version = run('pacman', '-Q', 'harness-os', timeout=10).split()
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return None
+ return version if name == 'harness-os' else None
+
+
+def restart_computer():
+ print('Restarting to finish the update…', flush=True)
+ subprocess.run(['systemctl', 'reboot'], check=True)
+
+
+def update_from_terminal(feeds=None, reboot=False):
"""`harness update`: everything Super+u updates, from a terminal, and what runs afterwards.
The same check and the same single decision as the Updates screen (update_all): the OS package
first when one is out, then hn and the CLI, the daemon restarted on the new CLI.
+
+ [reboot] (`--reboot`, a phone's Update): the person agreed to the restart on the phone, often with
+ nobody at the computer, so a system update restarts it at once instead of waiting for someone.
"""
if RESTART_REQUIRED.exists():
+ if reboot and read(RESTART_REQUIRED, {}).get('status') == 'ready':
+ restart_computer()
+ return 0
raise ValueError('Restart to finish the system update first: systemctl reboot')
print('Checking for updates…', flush=True)
check(feeds, progress=lambda line: print(' ' + line, flush=True) if line else None, force_system=True)
@@ -962,6 +989,9 @@ def update_from_terminal(feeds=None):
print('Updating Harness… Your agents keep running.', flush=True)
update_all()
if read(RESTART_REQUIRED, {}).get('status') == 'ready':
+ if reboot:
+ restart_computer()
+ return 0
print('The system is updated. Restart to finish: systemctl reboot '
'(hn and the CLI follow after the restart).')
return 0
diff --git a/os/root/etc/pacman.d/hooks/45-harness-unlock.hook b/os/root/etc/pacman.d/hooks/45-harness-unlock.hook
new file mode 100644
index 000000000..973e43cf7
--- /dev/null
+++ b/os/root/etc/pacman.d/hooks/45-harness-unlock.hook
@@ -0,0 +1,10 @@
+[Trigger]
+Operation = Install
+Operation = Upgrade
+Type = Path
+Target = usr/lib/initcpio/install/harness-unlock
+
+[Action]
+Description = Adding the phone unlock to an encrypted computer's startup
+When = PostTransaction
+Exec = /usr/lib/harness-os/enable-unlock
diff --git a/os/root/usr/lib/harness-os/enable-unlock b/os/root/usr/lib/harness-os/enable-unlock
new file mode 100755
index 000000000..2683cd7df
--- /dev/null
+++ b/os/root/usr/lib/harness-os/enable-unlock
@@ -0,0 +1,15 @@
+#!/bin/sh
+# An encrypted computer installed before the startup's hotspot (#1446, 0.1.7) updates to a package
+# that carries the harness-unlock hook, but its /etc/mkinitcpio.conf was written by the installer of
+# its day and never names it: it waits for its password at the screen only, and a phone finds no
+# Harness-XXXX. Placed before sd-encrypt, as installer.py writes it now, and the startup rebuilt.
+# From 45-harness-unlock.hook, after every install or upgrade of the hook; nothing to do once it is
+# there, on an unencrypted computer, or on the live USB.
+set -eu
+conf=${HARNESS_MKINITCPIO_CONF:-/etc/mkinitcpio.conf}
+[ -e /etc/harness-live ] && exit 0
+grep -Eq '^HOOKS=\(.*[ (]sd-encrypt[ )]' "$conf" || exit 0
+grep -Eq '^HOOKS=\(.*[ (]harness-unlock[ )]' "$conf" && exit 0
+sed -i -E 's/^(HOOKS=\(.*[ (])sd-encrypt([ )])/\1harness-unlock sd-encrypt\2/' "$conf"
+echo 'harness-unlock: the setup hotspot now comes up while the disk waits for its password'
+[ -n "${HARNESS_MKINITCPIO_CONF:-}" ] || mkinitcpio -P
diff --git a/os/tests/test_live_update.py b/os/tests/test_live_update.py
index b69e7f858..2996aee53 100644
--- a/os/tests/test_live_update.py
+++ b/os/tests/test_live_update.py
@@ -540,7 +540,7 @@ class FastUpdates(unittest.TestCase):
self.assertEqual(restart.call_count, 1)
self.assertFalse((self.state / 'approved.json').exists())
- def terminal_update(self, ready, daemon='1.1.0', system=False, errors=(), restart=None):
+ def terminal_update(self, ready, daemon='1.1.0', system=False, errors=(), restart=None, reboot=False):
"""`harness update` against a checked state; returns (exit, printed, update_all mock)."""
self.state.mkdir(exist_ok=True)
update.write(self.state / 'check.json', {'errors': list(errors)})
@@ -556,7 +556,7 @@ class FastUpdates(unittest.TestCase):
patch.object(update, 'selected', side_effect=lambda: running[0]), \
patch.object(update, 'update_all', side_effect=apply) as update_all, \
patch.object(update, 'daemon_version', return_value=daemon), patch('sys.stdout', printed):
- result = update.main(['update'])
+ result = update.main(['update', *(['--reboot'] if reboot else [])])
self.assertTrue(check.call_args.kwargs['force_system'])
return result, printed.getvalue(), update_all
@@ -586,6 +586,32 @@ class FastUpdates(unittest.TestCase):
update_all.assert_called_once()
self.assertIn('Restart to finish: systemctl reboot', printed)
+ def test_a_phones_update_restarts_for_the_system_and_only_for_it(self):
+ with patch.object(update.subprocess, 'run') as run:
+ self.terminal_update(None, system=True, restart='ready', reboot=True)
+ run.assert_called_once_with(['systemctl', 'reboot'], check=True)
+ update.RESTART_REQUIRED.unlink()
+ staged = self.root / 'staged'
+ staged.mkdir()
+ for name in update.FILES:
+ (staged / name).write_bytes(('new ' + name).encode())
+ with patch.object(update.subprocess, 'run') as run:
+ self.terminal_update(staged, reboot=True)
+ run.assert_not_called()
+ # An update applied earlier and waiting for its restart: the phone's Update is that restart.
+ update.RESTART_REQUIRED.write_text('{"status":"ready"}')
+ with patch.object(update.subprocess, 'run') as run:
+ self.assertEqual(update.update_from_terminal(reboot=True), 0)
+ run.assert_called_once_with(['systemctl', 'reboot'], check=True)
+ with self.assertRaisesRegex(SystemExit, '2'), patch('sys.stderr', io.StringIO()):
+ update.main(['status', '--reboot'])
+
+ def test_status_names_the_installed_os(self):
+ with patch.object(update, 'run', return_value='harness-os 0.1.7.r1-1'):
+ self.assertEqual(update.os_version(), '0.1.7.r1-1')
+ with patch.object(update, 'run', side_effect=subprocess.CalledProcessError(1, 'pacman')):
+ self.assertIsNone(update.os_version())
+
def test_terminal_update_refuses_while_a_restart_is_pending_and_when_nothing_could_be_checked(self):
with self.assertRaisesRegex(ValueError, 'could not be checked'):
self.terminal_update(None, errors=['offline'])
diff --git a/os/tests/test_unlock.py b/os/tests/test_unlock.py
index 90425f19c..575412d78 100644
--- a/os/tests/test_unlock.py
+++ b/os/tests/test_unlock.py
@@ -4,6 +4,7 @@ import json
import os
from pathlib import Path
import subprocess
+import sys
import tempfile
import unittest
@@ -158,5 +159,29 @@ class Unlock(unittest.TestCase):
self.assertEqual((self.root / 'given').read_text(), typed)
+ENABLE = Path(__file__).resolve().parents[1] / 'root/usr/lib/harness-os/enable-unlock'
+
+
[email protected](sys.platform.startswith('linux'), 'GNU sed, as on Harness OS')
+class EnableUnlock(unittest.TestCase):
+ """An encrypted computer installed before the startup's hotspot gets it with the package."""
+
+ def hooks_after(self, hooks):
+ with tempfile.TemporaryDirectory() as temp:
+ conf = Path(temp) / 'mkinitcpio.conf'
+ conf.write_text(f'HOOKS=({hooks})\nCOMPRESSION="zstd"\n')
+ subprocess.run(['sh', str(ENABLE)], check=True, capture_output=True,
+ env=dict(os.environ, HARNESS_MKINITCPIO_CONF=str(conf)))
+ return conf.read_text().splitlines()[0]
+
+ def test_it_goes_before_sd_encrypt_once_and_only_where_the_disk_is_encrypted(self):
+ before = 'base systemd autodetect microcode modconf kms keyboard sd-vconsole plymouth block sd-encrypt filesystems fsck'
+ after = before.replace('block sd-encrypt', 'block harness-unlock sd-encrypt')
+ self.assertEqual(self.hooks_after(before), f'HOOKS=({after})')
+ self.assertEqual(self.hooks_after(after), f'HOOKS=({after})')
+ plain = 'base systemd autodetect microcode modconf kms keyboard sd-vconsole block filesystems fsck'
+ self.assertEqual(self.hooks_after(plain), f'HOOKS=({plain})')
+
+
if __name__ == '__main__':
unittest.main()