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: updates take effect, `harness update`, Wi-Fi comes forward offline

bubu-dudue743d01859a5
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b91066f76..14f28259f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -40,7 +40,8 @@ import { registry } from './lib/registry.js'
import { readSafeModeMarker } from './lib/daemonSafeMode.js'
import { SpawnLockBusyError, describeSpawnLockBusyPlainly, describeSpawnLockFailure, describeSpawnLockOwner, describeSpawnLockWaitPlainly, withSpawnLock } from './lib/daemonSpawnLock.js'
import { stopDaemonProcess } from './lib/daemonStop.js'
-import { installedPlatform, serviceDefinition, startUnderPlatform } from './lib/platformDaemon.js'
+import { installedPlatform, osDaemonUnit, serviceDefinition, startUnderPlatform } from './lib/platformDaemon.js'
+import { askRuntimePort, readCgroup, takeRuntimeBack } from './lib/osUnitTakeover.js'
import { serviceCommand, serviceCommandDeps } from './lib/serviceCommand.js'
import { flashCommand } from './lib/flash.js'
import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE, type LoginCallbackParams } from './lib/loginCallback.js'
@@ -69,7 +70,7 @@ import { describeMasterStatus, readStatusFile } from './harnessd/master.js'
import { namedNode } from './harnessd/processName.js'
import { probeThisMaster, startMaster, startMasterInForeground } from './masterProcess.js'
import { startServiceProcess } from './serviceProcess.js'
-import { isLocalSocketName, localSocketPath, refuseServedDataFolder } from './lib/localSocket.js'
+import { askDataFolderServer, isLocalSocketName, localSocketPath, refuseServedDataFolder } from './lib/localSocket.js'
import { legacyDaemonStatus, localDaemonStatus } from './lib/daemonEndpoint.js'
import { runAutonomousDeviceCommand } from './lib/autonomous-device/command.js'
import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'
@@ -1386,6 +1387,23 @@ async function launch(foreground: boolean, repair: boolean = false): Promise<voi
const repaired = await repairManagedRuntimes(foreground)
if (repaired) runtimeNode = repaired
}
+ // Harness OS: run by harness-daemon.service, first take the runtime back from a daemon an older CLI
+ // started outside the unit, or this start finds it taken and the unit restarts in vain (osUnitTakeover.ts).
+ if (foreground && osDaemonUnit(process.platform, process.env)) {
+ const socket = localSocketPath(env.ADAPTER_DATA_DIR, env.PORT)
+ await takeRuntimeBack({
+ who: async () => {
+ const server = socket ? await askDataFolderServer(socket, 1_000) : 'none'
+ return typeof server === 'object' ? server : askRuntimePort(daemonPort())
+ },
+ cgroupOf: readCgroup,
+ alive: (pid) => isAlive(pid),
+ signal: (pid, signal) => process.kill(pid, signal),
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ now: () => Date.now(),
+ log: (line) => console.log(line),
+ })
+ }
// Foreground mode (a supervisor: launchd, systemd, a terminal) → harnessd's master in this process, as
// launchd and systemd run it, the core its child. The core ran here on its own before, and a core with no
// master must hand each update over itself (core/updateHandoff.ts). HARNESS_NO_MASTER=1 still runs the
diff --git a/cli/src/lib/connectors/connectors.spec.ts b/cli/src/lib/connectors/connectors.spec.ts
index 98998fccc..e9419625a 100644
--- a/cli/src/lib/connectors/connectors.spec.ts
+++ b/cli/src/lib/connectors/connectors.spec.ts
@@ -14,7 +14,7 @@ import { CATALOG, services } from './catalog.js'
import { addApiKey, addCustom, cards, customCode, disconnect, finish, Flows, signInFor } from './connect.js'
import * as gateway from './gateway.js'
import { LocalSignIn, probe } from './oauth.js'
-import { forgetPage, PageServer, rememberPage, runningPage } from './page.js'
+import { forgetPage, PAGE_BUILD, PageServer, rememberPage, runningPage } from './page.js'
import { refresh } from './renew.js'
import { call, OFFICIAL_HOSTS } from './call.js'
import { connectionsCommand } from './command.js'
@@ -451,11 +451,26 @@ describe('the page', () => {
it('is reused only when it proves it is ours, and forgotten only by itself', async () => {
rememberPage(vault, Number(new URL(page.origin).port), page.key)
expect(await runningPage(vault)).toBe(`${page.origin}/#${page.key}`)
- writePrivate(join(vault.root, 'page.json'), { port: Number(new URL(page.origin).port), key: 'not-this-servers' })
+ writePrivate(join(vault.root, 'page.json'), { port: Number(new URL(page.origin).port), key: 'not-this-servers', version: PAGE_BUILD, pid: 1 })
expect(await runningPage(vault)).toBeNull()
forgetPage(vault, Number(new URL(page.origin).port), 'not-this-servers')
expect(await runningPage(vault)).toBeNull()
})
+
+ it('is not reused when an earlier release runs it: that one is stopped, and a new page starts', async () => {
+ const port = Number(new URL(page.origin).port)
+ const stopped: number[] = []
+ rememberPage(vault, port, page.key, 'an-earlier-release', 4242)
+ expect(readPrivate(join(vault.root, 'page.json'))).toEqual({ port, key: page.key, version: 'an-earlier-release', pid: 4242 })
+ expect(await runningPage(vault, PAGE_BUILD, pid => stopped.push(pid))).toBeNull()
+ expect(stopped).toEqual([4242])
+ // One from before the release was written down: not reused, and with no pid, left to stop by itself.
+ writePrivate(join(vault.root, 'page.json'), { port, key: page.key })
+ expect(await runningPage(vault, PAGE_BUILD, pid => stopped.push(pid))).toBeNull()
+ expect(stopped).toEqual([4242])
+ rememberPage(vault, port, page.key)
+ expect(await runningPage(vault, PAGE_BUILD, pid => stopped.push(pid))).toBe(`${page.origin}/#${page.key}`)
+ })
})
describe('REST calls and the command', () => {
diff --git a/cli/src/lib/connectors/page.ts b/cli/src/lib/connectors/page.ts
index 4280bee84..0f3f8a202 100644
--- a/cli/src/lib/connectors/page.ts
+++ b/cli/src/lib/connectors/page.ts
@@ -5,13 +5,16 @@
*/
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
+import { statSync } from 'node:fs'
import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
import { addCustom, cards, disconnect, Flows, signInFor } from './connect.js'
import { services, type GatewayRow } from './catalog.js'
import { ICONS } from './generated/icons.js'
import { PAGE_FILES } from './generated/page.js'
import { ConnectorError, locked, readPrivate, validateCode, writePrivate, type Store } from './store.js'
import * as gateway from './gateway.js'
+import { VERSION } from '../../version.js'
const IDLE_MS = 15 * 60_000
const GATEWAY_CACHE_MS = 60_000
@@ -149,12 +152,22 @@ export class PageServer {
}
}
-/** The running page's address, when page.json names a live one that proves it is ours. */
-export async function runningPage(vault: Store): Promise<string | null> {
+/**
+ * The running page's address, when page.json names a live one that proves it is ours and runs this
+ * release. One an earlier release started (Harness OS's own CLI at the welcome screen, before an update)
+ * is not reused: it runs that release's code. One from before the account's connections (vaultSync.ts)
+ * disconnected without recording it, so the account's copy brought the connection straight back. It is
+ * asked to stop when its pid is known; one from before the pid was written stops once nothing opens it.
+ */
+export async function runningPage(vault: Store, version = PAGE_BUILD, stop = stopPage): Promise<string | null> {
let data: Record<string, unknown> | null
try { data = readPrivate(join(vault.root, 'page.json')) } catch { return null }
const port = data?.port
if (typeof port !== 'number' || port < 1024 || port > 65535 || typeof data!.key !== 'string') return null
+ if (data!.version !== version) {
+ if (typeof data!.pid === 'number') stop(data!.pid)
+ return null
+ }
const origin = `http://127.0.0.1:${port}`
// An unrelated process can reclaim an expired page's port: never send it the capability.
const nonce = randomBytes(32).toString('hex')
@@ -169,8 +182,26 @@ export async function runningPage(vault: Store): Promise<string | null> {
return null
}
-export function rememberPage(vault: Store, port: number, key: string): void {
- writePrivate(join(vault.root, 'page.json'), { port, key })
+/**
+ * This release and which build of it. An unreleased build says 0.0.1, as Harness OS's own CLI does, so
+ * the version alone cannot tell the OS image's page from an update's: the file running this can.
+ */
+function thisBuild(): string {
+ try {
+ const file = statSync(fileURLToPath(import.meta.url))
+ return `${VERSION}+${file.size}.${Math.round(file.mtimeMs)}`
+ } catch { return VERSION }
+}
+export const PAGE_BUILD = thisBuild()
+
+export function rememberPage(vault: Store, port: number, key: string, version = PAGE_BUILD, pid = process.pid): void {
+ writePrivate(join(vault.root, 'page.json'), { port, key, version, pid })
+}
+
+/** Stop an earlier release's page; one that is gone, or not ours to signal, is left alone. */
+function stopPage(pid: number): void {
+ if (pid === process.pid) return
+ try { process.kill(pid, 'SIGTERM') } catch { /* Gone already. */ }
}
/** A newer launcher may already own page.json: remove only this instance's. */
diff --git a/cli/src/lib/osUnitTakeover.spec.ts b/cli/src/lib/osUnitTakeover.spec.ts
new file mode 100644
index 000000000..e6ae15712
--- /dev/null
+++ b/cli/src/lib/osUnitTakeover.spec.ts
@@ -0,0 +1,91 @@
+import { createServer, type Server } from 'node:http'
+import { afterEach, describe, expect, it } from 'vitest'
+import { askRuntimePort, inUnit, readCgroup, takeRuntimeBack, type RuntimeServer, type TakeoverDeps } from './osUnitTakeover.js'
+
+const UNIT = '0::/user.slice/user-1000.slice/[email protected]/app.slice/harness-daemon.service\n'
+const SCREEN = '0::/user.slice/user-1000.slice/session-2.scope\n'
+
+/** A computer: who serves, each process's cgroup, which are alive, and what was done to them. */
+function computer(server: RuntimeServer, cgroups: Record<string, string | null>, options: { stubborn?: boolean } = {}) {
+ const alive = new Set(typeof server === 'object' ? [server.pid, server.corePid] : [])
+ const signals: [number, NodeJS.Signals][] = []
+ const lines: string[] = []
+ let now = 0
+ const deps: TakeoverDeps = {
+ who: async () => server,
+ cgroupOf: (pid) => cgroups[String(pid)] ?? null,
+ alive: (pid) => alive.has(pid),
+ signal: (pid, signal) => {
+ signals.push([pid, signal])
+ if (!options.stubborn || signal === 'SIGKILL') alive.delete(pid)
+ },
+ sleep: async (ms) => { now += ms },
+ now: () => now,
+ log: (line) => lines.push(line),
+ }
+ return { deps, signals, lines, alive }
+}
+
+describe('taking the agent runtime back for harness-daemon.service', () => {
+ it('stops a daemon an older CLI started outside the unit, master and core, and goes on', async () => {
+ const pc = computer({ pid: 300, corePid: 301 }, { self: UNIT, 300: SCREEN })
+ expect(await takeRuntimeBack(pc.deps)).toBe('stopped')
+ expect(pc.signals).toEqual([[300, 'SIGTERM'], [301, 'SIGTERM']])
+ expect(pc.lines[0]).toContain('outside harness-daemon.service (pid 300)')
+ })
+
+ it('ends one that does not stop in time', async () => {
+ const pc = computer({ pid: 300, corePid: 300 }, { self: UNIT, 300: SCREEN }, { stubborn: true })
+ expect(await takeRuntimeBack(pc.deps, 1_000)).toBe('stopped')
+ expect(pc.signals).toEqual([[300, 'SIGTERM'], [300, 'SIGKILL']])
+ expect(pc.lines[1]).toContain('did not stop within 1s')
+ })
+
+ it('leaves alone the unit\'s own daemon, one it cannot see, and every start that is not the unit\'s', async () => {
+ for (const [server, cgroups] of [
+ [{ pid: 300, corePid: 301 }, { self: UNIT, 300: UNIT }],
+ [{ pid: 300, corePid: 301 }, { self: UNIT, 300: null }],
+ [{ pid: 300, corePid: 301 }, { self: SCREEN, 300: SCREEN }],
+ [{ pid: 300, corePid: 301 }, { self: null, 300: SCREEN }],
+ ['none', { self: UNIT }],
+ ['unknown', { self: UNIT }],
+ ] as [RuntimeServer, Record<string, string | null>][]) {
+ const pc = computer(server, cgroups)
+ expect(await takeRuntimeBack(pc.deps)).toBe('none')
+ expect(pc.signals).toEqual([])
+ }
+ })
+
+ it('reads a cgroup line as the unit\'s only for harness-daemon.service itself', () => {
+ expect(inUnit(UNIT)).toBe(true)
+ expect(inUnit('0::/user.slice/[email protected]/app.slice/harness-daemon.service/core\n')).toBe(true)
+ expect(inUnit(SCREEN)).toBe(false)
+ expect(inUnit('0::/user.slice/[email protected]/app.slice/harness-daemon.service-old\n')).toBe(false)
+ expect(readCgroup(2 ** 30)).toBeNull()
+ })
+})
+
+describe('asking the runtime port who it is', () => {
+ let server: Server | null = null
+ afterEach(() => { server?.close(); server = null })
+
+ async function answering(body: string): Promise<number> {
+ server = createServer((_request, response) => response.end(body))
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
+ return (server.address() as { port: number }).port
+ }
+
+ it('reads the pid, and the core when the daemon has a master', async () => {
+ expect(await askRuntimePort(await answering('{"pid":12,"corePid":13}'))).toEqual({ pid: 12, corePid: 13 })
+ })
+
+ it('takes a daemon from before harnessd as its own core', async () => {
+ expect(await askRuntimePort(await answering('{"pid":12}'))).toEqual({ pid: 12, corePid: 12 })
+ })
+
+ it('is unknown when the answer names nobody, and none when nothing answers', async () => {
+ expect(await askRuntimePort(await answering('{"pid":"x"}'))).toBe('unknown')
+ expect(await askRuntimePort(await answering('not json'))).toBe('none')
+ expect(await askRuntimePort(1, 200)).toBe('none')
+ })
+})
diff --git a/cli/src/lib/osUnitTakeover.ts b/cli/src/lib/osUnitTakeover.ts
new file mode 100644
index 000000000..68ff38647
--- /dev/null
+++ b/cli/src/lib/osUnitTakeover.ts
@@ -0,0 +1,79 @@
+/**
+ * Harness OS: the agent runtime is harness-daemon.service's (platformDaemon.ts osDaemonUnit). A CLI from
+ * before that rule, the one an image ships for its welcome screen, starts a daemon of its own at sign-in,
+ * detached, outside the unit. It holds the data folder and the port, so after an update the unit's
+ * daemon found them taken and exited, again and again (230 restarts on an Orange Pi, 2026-10-13), the old
+ * runtime went on serving, and the update never took effect.
+ *
+ * Started by the unit, the daemon takes the runtime back first: one serving from outside the unit is
+ * stopped (the agents in tmux outlive it, as they outlive `harness stop`), and start-up goes on. A daemon
+ * inside the unit, the core of the unit's previous run, is left to refuseServedDataFolder's orphan wait.
+ */
+import { readFileSync } from 'node:fs'
+
+const UNIT = /\/harness-daemon\.service(\/|$)/m
+export const TAKEOVER_WAIT_MS = 30_000
+const POLL_MS = 250
+
+export type RuntimeServer = { pid: number, corePid: number } | 'none' | 'unknown'
+
+export interface TakeoverDeps {
+ /** Who serves the agent runtime: the data folder's socket, else the port's `/api/status`. */
+ who(): Promise<RuntimeServer>
+ /** A process's `/proc/<pid>/cgroup`, or null when it cannot be read. */
+ cgroupOf(pid: number | 'self'): string | null
+ alive(pid: number): boolean
+ signal(pid: number, signal: NodeJS.Signals): void
+ sleep(ms: number): Promise<void>
+ now(): number
+ log(line: string): void
+}
+
+/** Whether a `/proc/<pid>/cgroup` is harness-daemon.service's. */
+export function inUnit(cgroup: string): boolean {
+ return UNIT.test(cgroup)
+}
+
+/**
+ * Stop a daemon serving the runtime from outside harness-daemon.service when this process is the unit's.
+ * `none`: nothing to do (not the unit, nothing serving, or the unit's own). `stopped`: one was stopped.
+ */
+export async function takeRuntimeBack(deps: TakeoverDeps, waitMs = TAKEOVER_WAIT_MS): Promise<'none' | 'stopped'> {
+ const own = deps.cgroupOf('self')
+ if (own === null || !inUnit(own)) return 'none'
+ const server = await deps.who()
+ if (typeof server !== 'object') return 'none'
+ const theirs = deps.cgroupOf(server.pid)
+ // Unreadable is gone, or another user's: either way not ours to stop.
+ if (theirs === null || inUnit(theirs)) return 'none'
+ const pids = [...new Set([server.pid, server.corePid])]
+ deps.log(`[cli] a daemon started outside harness-daemon.service (pid ${server.pid}) serves the agent runtime — stopping it so this one runs`)
+ for (const pid of pids) { try { deps.signal(pid, 'SIGTERM') } catch { /* already gone */ } }
+ const deadline = deps.now() + waitMs
+ while (pids.some((pid) => deps.alive(pid))) {
+ if (deps.now() >= deadline) {
+ deps.log(`[cli] it did not stop within ${Math.round(waitMs / 1000)}s — ending it`)
+ for (const pid of pids) { try { deps.signal(pid, 'SIGKILL') } catch { /* already gone */ } }
+ break
+ }
+ await deps.sleep(POLL_MS)
+ }
+ return 'stopped'
+}
+
+/** Ask a daemon's loopback port who it is, as the OS updater does: every release answers there. */
+export async function askRuntimePort(port: string | number, timeoutMs = 1_000): Promise<RuntimeServer> {
+ try {
+ const response = await fetch(`http://127.0.0.1:${port}/api/status`, { signal: AbortSignal.timeout(timeoutMs) })
+ const status = await response.json() as { pid?: unknown, corePid?: unknown }
+ const pid = Number(status.pid)
+ const corePid = status.corePid === undefined ? pid : Number(status.corePid)
+ return Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(corePid) && corePid > 0 ? { pid, corePid } : 'unknown'
+ } catch {
+ return 'none'
+ }
+}
+
+export function readCgroup(pid: number | 'self'): string | null {
+ try { return readFileSync(`/proc/${pid}/cgroup`, 'utf8') } catch { return null }
+}
diff --git a/os/README.md b/os/README.md
index 5e5ed761c..ca490a5ea 100644
--- a/os/README.md
+++ b/os/README.md
@@ -16,11 +16,14 @@ After shutdown, remove the USB and boot the installed disk. If disconnected,
the Wi-Fi page opens first and advances automatically when connected; Ethernet
skips that step. OpenCode starts on the left with two real terminals on the right.
There is no trial choice or installation dock.
-
-**Next build:** the OS finishes Wi-Fi or Ethernet setup before launching hn.
-hn then requires a Harness account before opening the workspace. The USB
-installer remains available offline. An already signed-in account can reopen
-local work during a temporary network outage.
+The OS finishes Wi-Fi or Ethernet setup before launching hn, and hn requires a
+Harness account before opening the workspace; signing out returns to that page.
+An already signed-in account can reopen local work during a temporary network
+outage. When the network stays gone for 10 seconds, the Wi-Fi page comes forward
+by itself (over the sign-in page, or as a tab when signed in), once per outage.
+`harness update` updates everything Super+u does from a terminal, and says which
+version the daemon runs afterwards. After an update, the daemon always runs
+under `harness-daemon.service`, even where an older CLI started one beside it.
Later launches restore existing work. The installed system keeps hn’s standard
status bar. Ctrl+b, then c opens a terminal in a new tab. Projects live under
diff --git a/os/live_update.py b/os/live_update.py
index 8b682436e..725849a46 100644
--- a/os/live_update.py
+++ b/os/live_update.py
@@ -876,7 +876,7 @@ def screen(window, message='', refresh=False, intent=None):
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument('action', choices=['check', 'screen', 'request', 'apply', 'rollback', 'status'], nargs='?', default='screen')
+ 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)
args = parser.parse_args(argv)
@@ -901,6 +901,8 @@ def main(argv=None):
elif args.action == 'check':
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)
elif args.action == 'screen':
with screen_registration():
run_screen()
@@ -919,6 +921,50 @@ def main(argv=None):
'system': system_channel(), 'check': read(STATE / 'check.json')}, indent=2))
+def daemon_version():
+ """The version the running agent runtime reports, or None when nothing answers."""
+ try:
+ with urlopen(Request(DAEMON_STATUS), timeout=3) as response:
+ version = json.loads(response.read(65536)).get('version')
+ except (OSError, ValueError, AttributeError):
+ return None
+ return version if isinstance(version, str) and version else None
+
+
+def update_from_terminal(feeds=None):
+ """`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.
+ """
+ if RESTART_REQUIRED.exists():
+ 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)
+ errors = read(STATE / 'check.json', {}).get('errors') or []
+ for error in errors:
+ print(' could not check: ' + str(error), flush=True)
+ ready = prepared()
+ if not system_channel().get('available') and not (ready and ready != selected()):
+ if errors:
+ raise ValueError('Some updates could not be checked. Try again.')
+ running = versions(selected())
+ print(f"Harness is up to date: hn {running.get('hn')}, CLI {running.get('cli')}, daemon {daemon_version() or 'not answering'}.")
+ return 0
+ print('Updating Harness… Your agents keep running.', flush=True)
+ update_all()
+ if read(RESTART_REQUIRED, {}).get('status') == 'ready':
+ print('The system is updated. Restart to finish: systemctl reboot '
+ '(hn and the CLI follow after the restart).')
+ return 0
+ running = versions(selected())
+ daemon = daemon_version()
+ print(f"Updated: hn {running.get('hn')}, CLI {running.get('cli')}, daemon {daemon or 'not answering'}.")
+ if daemon != running.get('cli'):
+ raise ValueError(f"The daemon runs {daemon or 'nothing'}, not CLI {running.get('cli')}. Open Updates (Super+u) to see why.")
+ return 0
+
+
def run_screen():
message = ''
intent = UpdateIntent()
diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harness
index 267ce36e7..1cd5882bf 100644
--- a/os/root/usr/bin/harness
+++ b/os/root/usr/bin/harness
@@ -26,6 +26,12 @@ if [ "${1:-}" = rollback ]; then
shift
exec /usr/bin/python3 /usr/lib/harness-os/runtime_update.py rollback "$@"
fi
+if [ "${1:-}" = update ]; then
+ # Everything Super+u updates, from a terminal: the OS package, hn, the CLI and its daemon.
+ # The CLI's own self-update would only race the OS's activation (ADAPTER_UPDATE_DISABLE below).
+ shift
+ exec /usr/bin/python3 /usr/lib/harness-os/live_update.py update "$@"
+fi
if [ "${1:-}" = updates ]; then
shift
if [ -t 0 ] && [ -z "${SSH_CONNECTION:-}${SSH_TTY:-}" ] &&
diff --git a/os/root/usr/share/harness-os/guide.md b/os/root/usr/share/harness-os/guide.md
index fc22663a6..87f7aca60 100644
--- a/os/root/usr/share/harness-os/guide.md
+++ b/os/root/usr/share/harness-os/guide.md
@@ -123,6 +123,8 @@ conversation history. Describe only collaboration controls present in this TUI.
supported hardware. Display brightness keys keep a nonzero minimum; keyboard
illumination can be turned off independently.
- Super+u starts updates after installation; the Update button is clickable too.
+- `harness update` does the same from a terminal: the OS package when one is out, then hn, the CLI
+ and its daemon, and says which version the daemon runs afterwards. `harness --version` is the CLI's.
No confirmation or password is needed. Restart only when ready. Updates keep projects and running
work; flashing another USB is not the everyday update workflow.
diff --git a/os/tests/test_live_update.py b/os/tests/test_live_update.py
index 488bcf420..317646c3f 100644
--- a/os/tests/test_live_update.py
+++ b/os/tests/test_live_update.py
@@ -540,6 +540,67 @@ 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):
+ """`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)})
+ update.write(self.state / 'system.json', {'available': system})
+ printed = io.StringIO()
+ running = [self.bundled]
+ def apply():
+ if restart:
+ update.RESTART_REQUIRED.write_text(json.dumps({'status': restart}))
+ elif ready:
+ running[0] = ready
+ with patch.object(update, 'check') as check, patch.object(update, 'prepared', return_value=ready), \
+ 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'])
+ self.assertTrue(check.call_args.kwargs['force_system'])
+ return result, printed.getvalue(), update_all
+
+ def test_terminal_update_says_what_runs_when_nothing_is_newer(self):
+ result, printed, update_all = self.terminal_update(None, daemon='1.0.0')
+ self.assertEqual(result, 0)
+ update_all.assert_not_called()
+ self.assertIn('Harness is up to date: hn 1.0.0, CLI 1.0.0, daemon 1.0.0.', printed)
+
+ def test_terminal_update_applies_everything_and_checks_the_daemon_runs_it(self):
+ staged = self.root / 'staged'
+ staged.mkdir()
+ for name in update.FILES:
+ (staged / name).write_bytes(('new ' + name).encode())
+ result, printed, update_all = self.terminal_update(staged)
+ self.assertEqual(result, 0)
+ update_all.assert_called_once()
+ self.assertIn('Updated: hn 1.1.0, CLI 1.1.0, daemon 1.1.0.', printed)
+ with self.assertRaisesRegex(ValueError, 'The daemon runs 1.0.0, not CLI 1.1.0'):
+ self.terminal_update(staged, daemon='1.0.0')
+ with self.assertRaisesRegex(ValueError, 'The daemon runs nothing'):
+ self.terminal_update(staged, daemon=None)
+
+ def test_terminal_update_of_the_system_asks_for_the_restart(self):
+ result, printed, update_all = self.terminal_update(None, system=True, restart='ready')
+ self.assertEqual(result, 0)
+ update_all.assert_called_once()
+ self.assertIn('Restart to finish: systemctl reboot', printed)
+
+ 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'])
+ update.RESTART_REQUIRED.write_text('{"status":"ready"}')
+ with self.assertRaisesRegex(ValueError, 'Restart to finish the system update first'):
+ update.update_from_terminal()
+
+ def test_daemon_version_reads_the_runtime_status(self):
+ with patch.object(update, 'urlopen', return_value=Response(b'{"version":"0.3.89","pid":1}')):
+ self.assertEqual(update.daemon_version(), '0.3.89')
+ with patch.object(update, 'urlopen', return_value=Response(b'{"pid":1}')):
+ self.assertIsNone(update.daemon_version())
+ with patch.object(update, 'urlopen', side_effect=OSError('refused')):
+ self.assertIsNone(update.daemon_version())
+
def test_failed_privileged_update_does_not_authorize_later_activation(self):
self.state.mkdir()
update.write(self.state / 'system.json', {'available': True})
diff --git a/tui/src/account.rs b/tui/src/account.rs
index 7b2f64b39..7565c2f30 100644
--- a/tui/src/account.rs
+++ b/tui/src/account.rs
@@ -55,6 +55,11 @@ pub struct State {
pub fn entry_required(app: &App) -> bool { app.account.entry_required && !app.headless }
+/// Required sign-in with no attempt under way: what may be covered without losing a sign-in.
+pub fn entry_idle(app: &App) -> bool {
+ entry_required(app) && matches!(app.account.phase, Phase::Ready | Phase::Failed(_))
+}
+
/// Every interactive workspace needs an account, including the OS's bundled TUI.
/// Detached servers keep their sessions running.
pub fn begin_entry(app: &mut App) {
diff --git a/tui/src/os_welcome.rs b/tui/src/os_welcome.rs
index 022f75b50..270ed92de 100644
--- a/tui/src/os_welcome.rs
+++ b/tui/src/os_welcome.rs
@@ -17,8 +17,16 @@ pub struct State {
wifi_pane: Option<u64>,
install_tab: Option<String>,
wifi_tab: Option<String>,
+ /// The Wi-Fi form was opened for this spell offline; closed, it is not forced on again until the
+ /// computer has been online and lost its network once more.
+ offline_offered: bool,
+ /// When this spell offline began: a boot whose network is still coming up is not one.
+ offline_since: Option<std::time::Instant>,
}
+/// How long the network must stay gone before the Wi-Fi form comes forward by itself.
+pub const OFFLINE_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
+
pub fn live(app: &App) -> bool { app.os_session && app.os_live && !app.headless }
/// Only the locally created OS Wi-Fi form may cover required sign-in. Never
@@ -35,6 +43,51 @@ pub fn entry_wifi(app: &App) -> Option<u64> {
pub fn tick(app: &mut App) {
if !app.os_session || app.tick % 8 != 0 { return }
app.os_welcome.welcome_panes.retain(|id| app.panes.contains_key(id));
+ if !app.os_live && !app.headless {
+ offer_wifi(app, online(&read("/proc/net/route"), &read("/proc/net/ipv6_route")), std::time::Instant::now());
+ }
+}
+
+fn read(path: &str) -> String { std::fs::read_to_string(path).unwrap_or_default() }
+
+/// With the network gone, the Wi-Fi form comes forward by itself, once per spell offline, after the
+/// grace a boot or a roaming hop needs. On required sign-in it covers the sign-in page and closes back
+/// to it when it connects; signed in, it is a tab like Super+w's, and local work stays a tab away.
+/// Never in the middle of a sign-in, and never before this computer's daemon can run the form.
+pub fn offer_wifi(app: &mut App, online: bool, now: std::time::Instant) {
+ if online {
+ app.os_welcome.offline_offered = false;
+ app.os_welcome.offline_since = None;
+ return
+ }
+ let since = *app.os_welcome.offline_since.get_or_insert(now);
+ if app.os_welcome.offline_offered || now.duration_since(since) < OFFLINE_GRACE { return }
+ if crate::account::entry_required(app) {
+ if entry_wifi(app).is_some() || !crate::account::entry_idle(app) { return }
+ } else if app.read_only() || wifi_open(app) {
+ return
+ }
+ if app.link(&crate::input::shell_machine(app, None)).is_none() { return }
+ app.os_welcome.offline_offered = true;
+ local_dialog(app, "Wi-Fi", "/usr/bin/hn-os wifi", false);
+}
+
+/// The Wi-Fi form is already somewhere in the workspace: offering it again would only steal focus.
+fn wifi_open(app: &App) -> bool {
+ app.os_welcome.wifi_pane.is_some_and(|id| app.panes.get(&id).is_some_and(|pane| pane.dead.is_none()))
+}
+
+/// A route out of this computer: a default route, IPv4 or IPv6, on an interface that is up and not
+/// loopback (`/proc/net/route`, `/proc/net/ipv6_route`), which NetworkManager sets once it connects.
+pub fn online(v4: &str, v6: &str) -> bool {
+ let up = |flags: &str| u32::from_str_radix(flags, 16).is_ok_and(|flags| flags & 1 != 0);
+ v4.lines().skip(1).any(|line| {
+ let f: Vec<&str> = line.split_whitespace().collect();
+ f.len() > 3 && f[0] != "lo" && f[1] == "00000000" && up(f[3])
+ }) || v6.lines().any(|line| {
+ let f: Vec<&str> = line.split_whitespace().collect();
+ f.len() >= 10 && f[9] != "lo" && f[0].bytes().all(|b| b == b'0') && f[0].len() == 32 && f[1] == "00" && up(f[8])
+ })
}
fn split_starter(app: &mut App, pane: u64, dir: Dir, command: &str) {
@@ -310,6 +363,75 @@ mod tests {
assert!(!text.contains("PRIVATE_WORKSPACE_CONTENT"));
}
+ #[test]
+ fn online_needs_a_default_route_that_is_up_and_not_loopback() {
+ let head = "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n";
+ assert!(online(&format!("{head}wlan0\t00000000\t0101A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n"), ""));
+ assert!(!online(&format!("{head}wlan0\t0001A8C0\t00000000\t0001\t0\t0\t600\t00FFFFFF\t0\t0\t0\n"), ""), "a local subnet alone is not online");
+ assert!(!online(&format!("{head}wlan0\t00000000\t0101A8C0\t0002\t0\t0\t600\t00000000\t0\t0\t0\n"), ""), "a route that is down");
+ assert!(!online("", ""));
+ let zero = "0".repeat(32);
+ assert!(online("", &format!("{zero} 00 {zero} 00 fe800000000000000000000000000001 00000400 00000001 00000000 00000003 wlan0\n")));
+ assert!(!online("", &format!("{zero} 00 {zero} 00 {zero} ffffffff 00000001 00000000 00200200 lo\n")), "the kernel's unreachable default on lo");
+ }
+
+ /// An installed OS computer whose daemon can run the Wi-Fi form.
+ fn installed() -> App {
+ let mut app = fixture(100, 30);
+ app.os_live = false;
+ app.fleet.local_id = "local-daemon".into();
+ app.connect("local-daemon");
+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "local-daemon".into(), name: "This computer".into(),
+ local: true, status: "running".into(), reach: crate::fleet::Reach::Ready });
+ app
+ }
+
+ #[tokio::test]
+ async fn offline_brings_the_wifi_form_forward_after_the_grace_once_per_spell() {
+ use std::time::{Duration, Instant};
+ for signed_in in [false, true] {
+ let mut app = installed();
+ if !signed_in { crate::account::begin_entry(&mut app); }
+ assert_eq!(crate::account::entry_required(&app), !signed_in);
+ let start = Instant::now();
+ offer_wifi(&mut app, true, start);
+ assert!(app.os_welcome.wifi_tab.is_none(), "online: nothing changes");
+ offer_wifi(&mut app, false, start);
+ offer_wifi(&mut app, false, start + OFFLINE_GRACE - Duration::from_secs(1));
+ assert!(app.os_welcome.wifi_tab.is_none(), "a network still coming up is not offline");
+ offer_wifi(&mut app, false, start + OFFLINE_GRACE);
+ let opened = app.os_welcome.wifi_tab.clone();
+ assert!(opened.is_some(), "offline (signed in: {signed_in}): the Wi-Fi form opens");
+ assert_eq!(app.tab().id, *opened.as_ref().unwrap());
+ // Closed with Esc and still offline: it does not come back on every tick.
+ app.os_welcome.wifi_tab = None;
+ offer_wifi(&mut app, false, start + OFFLINE_GRACE * 3);
+ assert!(app.os_welcome.wifi_tab.is_none());
+ // Online again, then offline again past the grace: it comes forward again.
+ offer_wifi(&mut app, true, start + OFFLINE_GRACE * 4);
+ offer_wifi(&mut app, false, start + OFFLINE_GRACE * 4);
+ assert!(app.os_welcome.wifi_tab.is_none());
+ offer_wifi(&mut app, false, start + OFFLINE_GRACE * 5);
+ assert!(app.os_welcome.wifi_tab.is_some());
+ }
+ }
+
+ #[tokio::test]
+ async fn the_form_waits_for_the_daemon_and_never_interrupts_a_sign_in_or_a_read_only_client() {
+ use std::time::Instant;
+ let late = Instant::now() + OFFLINE_GRACE * 2;
+ let mut app = fixture(100, 30);
+ app.os_live = false;
+ offer_wifi(&mut app, false, Instant::now());
+ offer_wifi(&mut app, false, late);
+ assert!(app.os_welcome.wifi_tab.is_none(), "not before this computer's daemon can run the form");
+ let mut app = installed();
+ app.client_flags.push("read-only".into());
+ offer_wifi(&mut app, false, Instant::now());
+ offer_wifi(&mut app, false, late);
+ assert!(app.os_welcome.wifi_tab.is_none(), "a read-only client changes nothing");
+ }
+
#[tokio::test]
async fn install_reuses_its_local_form_even_when_a_remote_pane_is_focused() {
let mut app = fixture(120, 40);