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.

Simplify Harness first use and preserve newer runtime fixes (#710)

Deee3be3e0bfb53
diff --git a/.github/workflows/os.yml b/.github/workflows/os.yml
index 84159cd86..a50a88f95 100644
--- a/.github/workflows/os.yml
+++ b/.github/workflows/os.yml
@@ -71,6 +71,8 @@ jobs:
timeout-minutes: 50
steps:
- uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
- name: Record start and capacity
run: |
date -u
@@ -291,6 +293,8 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
- name: Check package and updater contracts
env:
OS_IMAGE_RUN: ${{ inputs.image_run_id }}
diff --git a/cli/src/dsh/install.ts b/cli/src/dsh/install.ts
index f394e92ce..803090ef8 100644
--- a/cli/src/dsh/install.ts
+++ b/cli/src/dsh/install.ts
@@ -270,7 +270,9 @@ function streamGit(args: string[], onLine: ((line: string) => void) | undefined)
}
})
child.on('error', (error) => { clearTimeout(timer); resolve({ ok: false, detail: error.message }) })
- child.on('exit', (code, signal) => {
+ // Exit may precede the last stderr data. Classify the failure only once
+ // the pipe closes, so a retryable Git error cannot become an empty one.
+ child.on('close', (code, signal) => {
clearTimeout(timer)
if (rest.trim()) { onLine?.(rest.trim()); tail.push(rest.trim()) }
if (code === 0) { resolve({ ok: true }); return }
diff --git a/cli/src/dsh/installProcess.spec.ts b/cli/src/dsh/installProcess.spec.ts
new file mode 100644
index 000000000..ea82b87d7
--- /dev/null
+++ b/cli/src/dsh/installProcess.spec.ts
@@ -0,0 +1,50 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { EventEmitter } from 'node:events'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { setImmediate } from 'node:timers/promises'
+import { env } from '../config/env.js'
+import { cloneInstall } from './install.js'
+
+const { spawn } = vi.hoisted(() => ({ spawn: vi.fn() }))
+vi.mock('node:child_process', async (original) => ({
+ ...await original<typeof import('node:child_process')>(), spawn,
+}))
+
+let directory: string
+let previous: string
+beforeEach(() => {
+ directory = mkdtempSync(join(tmpdir(), 'harness-git-drain-'))
+ previous = env.DSH_DIR
+ env.DSH_DIR = directory
+})
+afterEach(() => {
+ env.DSH_DIR = previous
+ spawn.mockReset()
+ rmSync(directory, { recursive: true, force: true })
+})
+
+it('waits for Git stderr to drain after exit before classifying a failed clone', async () => {
+ const child = Object.assign(new EventEmitter(), { stderr: new EventEmitter(), kill: vi.fn() })
+ spawn.mockReturnValue(child)
+ const lines: string[] = []
+ const pending = cloneInstall('https://example.test/repo.git', undefined, undefined, line => lines.push(line), [])
+ let settled = false
+ void pending.then(() => { settled = true })
+
+ // Node can report process exit before the final pipe data. Only close means
+ // the output is complete, including the reason used to decide a retry.
+ child.emit('exit', 128, null)
+ await setImmediate()
+ const settledBeforeOutput = settled
+ child.stderr.emit('data', Buffer.from('error: RPC failed; curl 28 Operation too slow\nfatal: early EOF'))
+ child.emit('close', 128, null)
+
+ expect(await pending).toEqual({
+ ok: false, error: 'CLONE_FAILED',
+ detail: 'git clone exited 128: error: RPC failed; curl 28 Operation too slow · fatal: early EOF · gave up after 1 attempts',
+ })
+ expect(settledBeforeOutput).toBe(false)
+ expect(lines).toEqual(['error: RPC failed; curl 28 Operation too slow', 'fatal: early EOF'])
+})
diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.ts
index d53b12583..381f54ea2 100644
--- a/cli/src/lib/projectFolder.spec.ts
+++ b/cli/src/lib/projectFolder.spec.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './projectFolder.js'
+import { parseProjectFolder, prepareProjectFolder, ProjectFolderError, projectsRoot } from './projectFolder.js'
describe('project folder preparation', () => {
let root: string
@@ -102,3 +102,13 @@ describe('project folder preparation', () => {
expect(await readdir(root)).toEqual(['repo'])
})
})
+
+// The OS chooses a familiar project root without changing other hn installations.
+it('uses lowercase projects only in the explicit Harness OS environment', () => {
+ try {
+ vi.stubEnv('HARNESS_OS', '1')
+ expect(projectsRoot('/home/me')).toBe('/home/me/projects')
+ vi.stubEnv('HARNESS_OS', '')
+ expect(projectsRoot('/Users/me')).toBe('/Users/me/harnesses')
+ } finally { vi.unstubAllEnvs() }
+})
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index f302646f4..117d5af3b 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -15,7 +15,7 @@ export type ProjectFolder = { source: 'new'; name?: string; suggested?: boolean
/** Where this daemon and the desktop app put the workspaces they make. A folder directly inside it is
* one of those; anywhere else is a folder the person chose and answers for themselves. */
export function projectsRoot(home = homedir()): string {
- return join(home, 'harnesses')
+ return join(home, process.env.HARNESS_OS === '1' ? 'projects' : 'harnesses')
}
export class ProjectFolderError extends Error {
diff --git a/docs/naming-system.md b/docs/naming-system.md
index a366da32e..061493ab7 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -107,11 +107,11 @@ configuration where it affects a decision.
| USB install action | **Install Harness** |
| Offline USB action | **Install without connecting** |
| USB dock invitation | **Make Harness your OS.** |
-| USB dock session label | **Temporary USB** |
+| USB session label | Omit from the single installation footer. |
| Connect another execution machine | **Connect a computer** |
-| Installer title | **Install Harness** |
+| Installer title | Omit the redundant heading; label the action. |
| Installer fields | **Disk**, **Encryption**, **Password**, **Repeat password** |
-| Installer action | **Install** |
+| Installer action | **Install Harness** |
| Installation completion | **Harness is installed.** |
| Completion actions | **Shut down**, **Back to Harness** |
| Default account | `me` |
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.md
index 154827dcd..07efa0c5f 100644
--- a/os/DEVELOPMENT.md
+++ b/os/DEVELOPMENT.md
@@ -358,7 +358,7 @@ Independent background agent updates remain future work and must preserve the
packaged fallback, validate provenance, avoid downgrades, and activate on a later
launch rather than replacing an active executable.
-Trial transfer reads only `~/Projects` as the live user, using a private staging
+Trial transfer reads only `~/projects` as the live user, using a private staging
directory on the destination disk. It preserves saved bytes, modes, times, Git
history and symlinks without following them. Special files and detected concurrent
writes fail explicitly. The installed home gets a per-file hash receipt. It is a
diff --git a/os/INSTALL.md b/os/INSTALL.md
index 93b0f7b5c..e894c8bf3 100644
--- a/os/INSTALL.md
+++ b/os/INSTALL.md
@@ -1,7 +1,7 @@
# Install Harness on a ThinkPad
These instructions are for **0.1.0-preview.9**, using a Mac to prepare the USB.
-The USB starts a live session. Installation begins only when you choose **Install**
+The USB starts a live session. Installation begins only when you choose **Install Harness**
in the installer; it erases the entire selected disk.
## 1. Prepare
@@ -64,19 +64,20 @@ The exact menu wording varies by model. See Lenovo's
[boot-menu instructions](https://docs.lenovocdrt.com/ref/bios/startup_menu/).
If the USB is absent, try another USB port and check that USB boot is enabled.
-The USB opens **Connect to Wi-Fi** and **Install without connecting** when offline.
-Choose Wi-Fi and enter its password in the system form to try an agent. Ethernet
+The USB opens a full-page Wi-Fi list with **Install without connecting** always
+visible. Choose a network and enter its password; a successful connection advances
+automatically. Ethernet
skips this step when already connected. No Harness account is needed.
-OpenCode starts with its default model selection. Beside it are **New Harness**
-and **Connect a computer**, for trying multiple agents and computers. Ask the agent
-about Harness, its shortcuts, or something you want to build. The bottom dock keeps
-**Install Harness** visible throughout the trial; **Temporary USB** reminds you
-that work has not yet been saved to an installed system.
+OpenCode starts with its default model selection on the left, beside two real
+terminal panes on the right. **Super+n** starts another harness; **Super+m**
+connects a computer. Ask the agent
+about Harness, its shortcuts, or something you want to build. The footer keeps
+**Install Harness** visible throughout the trial, beside the window list on one row.
-Create projects under `~/Projects`. The installer preserves and verifies these
+Create projects under `~/projects`. The installer preserves and verifies these
saved files, including Git history. Files elsewhere, running processes and agent
-credentials outside Projects are not copied. Save and stop project writes before
+credentials outside projects are not copied. Save and stop project writes before
installing, or copy important work to another drive.
### Trying an older Intel Mac
@@ -101,21 +102,21 @@ IDs and driver names, without serial numbers or Wi-Fi passwords.
## 5. Install
Choose **Install without connecting** at the network step, click **Install Harness**
-in the bottom dock, press **Super+i**, or ask the agent to open installation.
-F10 focuses the dock; Tab selects a button and Enter activates it. All routes open
+in the footer, press **Super+i**, or ask the agent to open installation.
+F10 focuses Install Harness in the footer; Enter opens it. All routes open
the same native form, with four fields:
-1. **Disk:** press Enter, choose the internal disk by its model and capacity, and
- press Enter again. The live USB is excluded from the choices.
+1. **Disk:** the first eligible disk is selected. Check its model and capacity.
+ To change it, focus Disk and press Enter. The live USB is excluded.
2. **Encryption:** enabled initially. Use Space to change it if needed.
-3. **Password:** enter the password for your new system.
+3. **Password:** focused when the form opens; type your new system password.
4. **Repeat password:** enter it again.
Use Tab or the arrow keys to move between fields. This preview uses a **US keyboard
layout**, including at disk unlock. Passwords cannot be empty; there is no minimum
length restriction.
-Check the selected disk, then choose **Install** and press Enter. **This immediately
+Check the selected disk, then choose **Install Harness** and press Enter. **This immediately
erases that disk. There is no second confirmation screen.** Choosing a disk alone
does not start installation. Esc leaves the picker or cancels the main form.
@@ -138,9 +139,9 @@ The password initially protects both the account and, when enabled, the encrypte
disk. Changing the account password later does not change the disk password.
There is no cloud account that resets the disk password.
-On the empty home screen, press **Enter** to start OpenCode. If there is no network
-connection, the keyboard network picker opens first. Select your Wi-Fi network
-and enter its password there. **Super+w** opens network setup from any
+First boot opens OpenCode on the left and two terminal panes on the right.
+If disconnected, Wi-Fi opens first; you can connect or continue offline.
+Subsequent launches restore your existing work. **Super+w** opens network setup from any
pane. Ethernet connects automatically when available.
OpenCode is already installed and uses its upstream defaults. Available models
@@ -169,23 +170,29 @@ the next key. A capital letter in a prefix binding means Shift + letter.
| `sudo systemctl poweroff` | Shut down |
Claude Code, Codex, OpenCode and pi each run in their own pane. Let the agent
-install the tools the project needs. Save work under `~/Projects`.
+install the tools the project needs. Save work under `~/projects`.
## 8. Updates
A small **Update ready · Super+u** notice appears when a new hn or CLI release
has downloaded and passed its checks. Press **Super+u**, then Enter to apply it.
The screen reconnects; your running agents and terminal processes remain.
-Use **R** in Updates to restore the previous runtime if needed.
+Use **r** in Updates to restore the previous runtime if needed.
-System updates use **S** in the same screen and ask for your account password.
+System updates use **s** in the same screen and ask for your account password.
They retain a recovery checkpoint and rebuild the boot image. When the screen
offers **Restart now**, save your work and press Enter when ready. Downloads do
not restart the computer, and routine updates do not require another USB flash.
-Preview 9 fixes a transient encrypted-disk cleanup failure after installation.
-An installed computer that boots successfully needs no update or reflash for this
-fix. The installed-system feed remains on preview 7.
+Preview 5 through 8 can receive preview 9 through **Super+u**, then **s**.
+It includes the new network page, first-use workspace, lowercase project folders,
+and the fix preventing older public CLI releases from replacing the bundled
+OpenCode compatibility code. Running work is preserved; save before restarting.
+No reinstallation or USB flash is needed for these installed-system changes.
+
+Preview 9 also fixes a transient encrypted-disk cleanup failure in the USB
+installer. A computer that already boots successfully needs no reinstallation
+for that cleanup fix.
Preview 4 needs the 7.2 MB [preview 7 bootstrap bundle](https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.7/harness-update-0.1.0-preview.7-47872670a-x86_64.zip)
once. Verify and extract that bundle, open a terminal in its folder, and run:
@@ -203,7 +210,7 @@ same folder before trying again.
1. Boot with the USB removed. Confirm disk unlock and the Harness home screen.
2. Connect Wi-Fi, open a terminal, type a command, and exit with Ctrl+D.
-3. Start OpenCode and ask it to build a small website in `~/Projects/hello`, run
+3. Start OpenCode and ask it to build a small website in `~/projects/hello`, run
its server, and give you the address. Open it with `hn-browser ADDRESS`.
4. Ask an agent to build and test a command-line program, installing tools as needed.
5. Switch between Harness and the browser. Lock and unlock the computer.
diff --git a/os/README.md b/os/README.md
index f4d113e79..f99f517ac 100644
--- a/os/README.md
+++ b/os/README.md
@@ -13,17 +13,21 @@ Product names and interface copy follow the [Naming System](../docs/naming-syste
**Preview 9:** the USB opens a short network step
or goes straight into bundled OpenCode when already connected. **Install without
-connecting** opens the same native installer offline. The agent works beside
-**New Harness** and **Connect a computer** starter panels; a persistent install
-dock keeps the USB's temporary state clear. Saved `~/Projects` files are copied
+connecting** opens the same native installer offline. OpenCode starts on the left with two real terminal panes on the right.
+The single footer holds the window list on the left and **Make Harness your OS.
+[ Install Harness ]** on the right. Installed first boot uses the same workspace;
+later launches restore existing work. Saved `~/projects` files are copied
and verified during installation. The full TUI reference and OS guide are bundled
for agent questions. **Super+n/t/m/i/w** require no Shift; Ctrl+b bindings still work.
-The installer has four fields and one Install action; encrypted boot shows the
+The installer selects a disk, focuses Password, and has one full-width
+**Install Harness** action. Progress shows only the current step; encrypted boot shows the
Harness wordmark and a masked password prompt.
Both the live and installed system use `me@harness`.
`Super+u` opens Updates. Frequent hn/CLI releases download in the background;
you choose when to reconnect the screen. Running agents and terminals stay alive.
+The update checker records release ancestry so a source-built runtime cannot be
+replaced by an older public CLI with a higher development version number.
[Download preview 9](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.9)
· [Mac → USB → ThinkPad installation guide](INSTALL.md)
@@ -143,13 +147,13 @@ In the current source, the USB asks for a network connection before opening
OpenCode. Choose **Install without connecting** to install immediately offline.
Ethernet skips the network step when already connected. During a trial, click
**Install Harness**, press **Super+i**, or ask the agent to open installation.
-F10 focuses the dock; Tab selects a button and Enter activates it. New Harness
+F10 focuses Install Harness in the footer; Enter opens the form. New Harness
and Connect a computer introduce multiple agents and computers; dismiss those
starter panels with their close button when the agent needs the whole screen.
-Saved files under `~/Projects`, including Git history, are transferred into the
+Saved files under `~/projects`, including Git history, are transferred into the
installed home and verified by hash. Work elsewhere remains temporary. Running
-processes and agent credentials outside Projects are not transferred. Stop writes
+processes and agent credentials outside projects are not transferred. Stop writes
to a project before installing; files changing during transfer are an error.
Preview 6's older welcome uses Enter to install or T to try and does not transfer
trial files; use the installation guide shipped with your image.
diff --git a/os/installer.py b/os/installer.py
index d74c0fcff..145aac1c1 100644
--- a/os/installer.py
+++ b/os/installer.py
@@ -228,7 +228,7 @@ def trial_source(config):
if not Path('/etc/harness-live').is_file():
return None
account = pwd.getpwnam('me')
- source = Path(account.pw_dir) / 'Projects'
+ source = Path(account.pw_dir) / 'projects'
if not source.exists():
return None
required = trial_command('size', source, account)['bytes']
@@ -245,7 +245,7 @@ def preserve_trial(trial, target, home):
# A root-owned parent keeps other live processes from changing the destination.
# Only this child receives the open writable directory, then drops privileges.
with tempfile.TemporaryDirectory(prefix='.harness-trial-', dir=target / 'home') as temp:
- staging = Path(temp) / 'Projects'
+ staging = Path(temp) / 'projects'
staging.mkdir(mode=0o700)
os.chown(staging, account.pw_uid, account.pw_gid)
descriptor = os.open(staging, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
@@ -253,8 +253,8 @@ def preserve_trial(trial, target, home):
receipt = trial_command('copy', source, account, descriptor)
finally:
os.close(descriptor)
- shutil.rmtree(home / 'Projects') # Only the new account's pristine skeleton.
- staging.rename(home / 'Projects')
+ shutil.rmtree(home / 'projects') # Only the new account's pristine skeleton.
+ staging.rename(home / 'projects')
detail = home / '.local/state/harness-os/trial-projects.json'
detail.parent.mkdir(parents=True, exist_ok=True)
detail.write_text(json.dumps(receipt, indent=2) + '\n')
@@ -338,7 +338,7 @@ def install(config, source, target, progress=None):
# disk initramfs around this verified, package-owned kernel instead.
shutil.copyfile(target / kernel['path'], target / 'boot/vmlinuz-linux-lts')
report('Setting up your account…')
- # The live image is immutable. Only Projects is transferred explicitly;
+ # The live image is immutable. Only projects is transferred explicitly;
# live account passwords, agent credentials, SSH keys and sessions stay out.
for path in ['etc/sudoers.d/10-live', 'etc/mkinitcpio.conf.d/archiso.conf',
'etc/systemd/system/[email protected]/live.conf',
@@ -354,7 +354,7 @@ def install(config, source, target, progress=None):
(target / 'var/lib/systemd/linger/me').unlink(missing_ok=True)
write(target, f'/var/lib/systemd/linger/{config["username"]}', '')
home = target / 'home' / config['username']
- (home / 'Projects').mkdir(exist_ok=True)
+ (home / 'projects').mkdir(exist_ok=True)
if trial is not None:
report('Keeping your trial projects…')
trial_receipt = preserve_trial(trial, target, home)
@@ -474,7 +474,7 @@ class InstallForm:
def __init__(self, screen, candidates, username, hostname, encrypt):
self.screen, self.disks = screen, candidates
self.username, self.hostname, self.encrypt = username, hostname, encrypt
- self.selected, self.focus = 0, 0
+ self.selected, self.focus = 0, 2
self.passwords, self.positions = ['', ''], [0, 0]
self.error = ''
self.title = None
@@ -495,7 +495,7 @@ class InstallForm:
row += self.top
if row >= height or width < 5:
return
- attr = curses.A_REVERSE if active else self.accent if accent else curses.A_BOLD if bold else curses.A_NORMAL
+ attr = (curses.A_REVERSE if active else self.accent if accent else curses.A_NORMAL) | (curses.A_BOLD if bold else 0)
self.screen.addnstr(row, self.left, text, min(self.width, width - self.left - 1), attr)
def cursor(self, visible):
@@ -530,7 +530,8 @@ class InstallForm:
for row, word in enumerate(WORDMARK):
self.line(row, word.center(self.width), accent=True)
self.top += 4
- self.line(1, title, bold=True)
+ if title:
+ self.line(1, title, bold=True)
return True
def key(self):
@@ -594,7 +595,7 @@ class InstallForm:
def run(self):
self.screen.keypad(True)
while True:
- if not self.begin('Install Harness'):
+ if not self.begin(''):
continue
disk = self.disks[self.selected]
# Identical models/capacities need a visible discriminator after selection.
@@ -610,8 +611,8 @@ class InstallForm:
mask = '*' * len(self.passwords[index][offset:offset + capacity])
self.line(8 + index * 2, f'{label:<18}[{mask:<{capacity}}]', self.focus == index + 2)
self.line(12, self.error)
- self.line(14, f"{'':18}[ Install ]", self.focus == 4)
- self.line(16, 'All data on this disk will be erased.')
+ for row, text in [(13, ''), (14, 'Install Harness'), (15, '')]:
+ self.line(row, text.center(self.width), active=True, bold=self.focus == 4)
self.cursor(self.focus in (2, 3))
if self.focus in (2, 3):
position = self.positions[self.focus - 2]
@@ -703,16 +704,8 @@ def install_with_progress(screen, config, source, target):
# A resize must never pause a disk operation waiting for keyboard input.
screen.erase()
height, width = screen.getmaxyx()
- view.width = max(1, min(60, width - 4))
- view.left = max(0, (width - view.width) // 2)
- view.top = max(0, (height - 12) // 2)
- if height >= 18:
- for row, word in enumerate(WORDMARK):
- view.line(row, word.center(view.width), accent=True)
- view.top += 4
- view.line(1, 'Installing Harness', bold=True)
- view.line(4, message)
- view.line(6, 'Keep this computer powered on.')
+ if height > 0 and width > 1:
+ screen.addnstr(height // 2, max(0, (width - len(message)) // 2), message, width - 1)
screen.refresh()
def progress(message):
diff --git a/os/live_update.py b/os/live_update.py
index 44d67d37a..39822962e 100644
--- a/os/live_update.py
+++ b/os/live_update.py
@@ -271,6 +271,10 @@ def check(feeds=None, progress=lambda _: None, force_system=False):
ready = None
base = ready if ready and ready.exists() else current
base_versions = verify(base)['versions'] if base != BUNDLED else running
+ # The OS is built from source, where the CLI can still call itself 0.0.1.
+ # Releases whose tagged commits are already ancestors of that source are
+ # older, even if their public version number is numerically higher.
+ baselines = read(BASE_ID, {}).get('release_baselines', {})
changes, target_versions, errors = {}, dict(base_versions), []
ignored = read(STATE / 'ignored.json', {})
for component, url in (feeds or FEEDS).items():
@@ -278,7 +282,8 @@ def check(feeds=None, progress=lambda _: None, force_system=False):
candidate, refs = release(url, component)
if ignored.get(component) == candidate:
continue
- if version(candidate) > version(base_versions[component]):
+ baseline = baselines.get(component, {}).get('version', '0.0.0')
+ if version(candidate) > max(version(base_versions[component]), version(baseline)):
progress('Downloading hn…' if component == 'hn' else 'Downloading Harness…')
component_files = {}
for name, ref in refs.items():
diff --git a/os/lock.json b/os/lock.json
index 116ff6c6e..8e6d6139d 100644
--- a/os/lock.json
+++ b/os/lock.json
@@ -3,9 +3,25 @@
"arch_snapshot": "2026/10/01",
"architecture": "x86_64",
"upgrades_from": [
- {"version": "0.1.0-preview.7", "arch_snapshot": "2026/10/01"},
- {"version": "0.1.0-preview.6", "arch_snapshot": "2026/10/01"},
- {"version": "0.1.0-preview.5", "arch_snapshot": "2026/10/01"},
- {"version": "0.1.0-preview.4", "arch_snapshot": "2026/10/01"}
+ {
+ "version": "0.1.0-preview.8",
+ "arch_snapshot": "2026/10/01"
+ },
+ {
+ "version": "0.1.0-preview.7",
+ "arch_snapshot": "2026/10/01"
+ },
+ {
+ "version": "0.1.0-preview.6",
+ "arch_snapshot": "2026/10/01"
+ },
+ {
+ "version": "0.1.0-preview.5",
+ "arch_snapshot": "2026/10/01"
+ },
+ {
+ "version": "0.1.0-preview.4",
+ "arch_snapshot": "2026/10/01"
+ }
]
}
diff --git a/os/network.py b/os/network.py
new file mode 100644
index 000000000..6f827cacc
--- /dev/null
+++ b/os/network.py
@@ -0,0 +1,327 @@
+#!/usr/bin/env python3
+"""A full-page Wi-Fi step backed by NetworkManager, with no resident UI service."""
+import argparse
+import curses
+import os
+from pathlib import Path
+import subprocess
+import time
+import uuid
+import unicodedata
+
+WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
+INSTALL = 10
+OFFLINE = 11
+
+
+def nmcli(*args, secret=None, wait=8):
+ # Secrets travel through stdin, never argv, shell text or diagnostic logs.
+ return subprocess.run(['/usr/bin/nmcli', '--colors', 'no', '--wait', str(wait), *args],
+ input=secret, capture_output=True, text=True, timeout=wait + 3,
+ env=dict(os.environ, LC_ALL='C'))
+
+
+def fields(line):
+ values, value, escaped = [], '', False
+ for character in line:
+ if escaped:
+ value += character
+ escaped = False
+ elif character == '\\':
+ escaped = True
+ elif character == ':':
+ values.append(value)
+ value = ''
+ else:
+ value += character
+ if escaped:
+ value += '\\'
+ return [*values, value]
+
+
+def connected():
+ try:
+ result = nmcli('-t', '-f', 'STATE', 'general', wait=2)
+ return result.returncode == 0 and result.stdout.strip().startswith('connected')
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+
+
+def scan(rescan=True):
+ result = nmcli('-t', '-e', 'yes', '-f', 'SSID,SIGNAL,SECURITY,DEVICE,BSSID,IN-USE',
+ 'device', 'wifi', 'list', '--rescan', 'yes' if rescan else 'no', wait=10)
+ if result.returncode:
+ raise ValueError('Could not scan Wi-Fi. Check airplane mode, then choose Rescan.')
+ networks = {}
+ for line in result.stdout.splitlines():
+ row = fields(line)
+ if len(row) != 6 or not row[0] or not row[1].isdigit():
+ continue
+ ssid, signal, security, device, bssid, active = row
+ item = dict(ssid=ssid, signal=int(signal), security=security, device=device,
+ bssid=bssid, active=active == '*')
+ key = (ssid, device, security)
+ if key not in networks or (item['active'], item['signal']) > (networks[key]['active'], networks[key]['signal']):
+ networks[key] = item
+ return sorted(networks.values(), key=lambda row: (not row['active'], -row['signal'], row['ssid']))
+
+
+def wired_devices():
+ result = nmcli('-t', '-e', 'yes', '-f', 'DEVICE,TYPE,STATE', 'device', 'status', wait=3)
+ if result.returncode:
+ return []
+ return [row for line in result.stdout.splitlines()
+ if len(row := fields(line)) == 3 and row[1] == 'ethernet' and row[2] != 'unavailable']
+
+
+def saved_connection(network):
+ result = nmcli('-t', '-f', 'UUID,TYPE', 'connection', 'show', wait=3)
+ if result.returncode:
+ return None
+ for line in result.stdout.splitlines():
+ row = fields(line)
+ if len(row) != 2 or row[1] != '802-11-wireless':
+ continue
+ detail = nmcli('-g', '802-11-wireless.ssid', 'connection', 'show', 'uuid', row[0], wait=3)
+ if detail.returncode == 0 and detail.stdout.rstrip('\n') == network['ssid']:
+ return row[0]
+ return None
+
+
+def connect(network, password=None):
+ saved = saved_connection(network) if password is None else None
+ if saved:
+ return nmcli('connection', 'up', 'uuid', saved, 'ifname', network['device'], wait=30).returncode == 0
+ security = network['security']
+ protected = bool(security and security != '--')
+ if protected and password is None:
+ return False
+ if '802.1X' in security or 'WEP' in security:
+ raise ValueError('This network needs advanced settings. Use nmcli in a terminal to configure it.')
+ if password is not None and ('\n' in password or '\r' in password):
+ raise ValueError('Enter the Wi-Fi password on one line.')
+ identity = str(uuid.uuid4())
+ arguments = ['connection', 'add', 'type', 'wifi', 'ifname', network['device'],
+ 'con-name', network['ssid'], 'connection.uuid', identity,
+ 'connection.autoconnect', 'no', 'ssid', network['ssid']]
+ 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']
+ created = nmcli(*arguments)
+ if created.returncode:
+ raise ValueError('Could not configure Wi-Fi. Choose Rescan and try again.')
+ succeeded = False
+ try:
+ arguments = ['connection', 'up', 'uuid', identity, 'ifname', network['device']]
+ secret = None
+ if protected:
+ arguments += ['passwd-file', '/dev/stdin']
+ secret = '802-11-wireless-security.psk:' + password + '\n'
+ result = nmcli(*arguments, secret=secret, wait=35)
+ if result.returncode:
+ return False
+ # Only a connected profile becomes eligible for automatic reconnection.
+ result = nmcli('connection', 'modify', 'uuid', identity, 'connection.autoconnect', 'yes')
+ if result.returncode:
+ raise ValueError('Connected, but could not save automatic reconnection. Try again.')
+ succeeded = True
+ return True
+ finally:
+ if not succeeded:
+ # Delete only the profile this attempt created, never an existing one.
+ try:
+ nmcli('connection', 'delete', 'uuid', identity)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+
+
+def clean(text):
+ return ''.join(character if character.isprintable() else ' ' for character in text)
+
+
+def fit(text, width):
+ result, used = '', 0
+ for character in clean(text):
+ cells = 0 if unicodedata.combining(character) else 2 if unicodedata.east_asian_width(character) in ('W', 'F') else 1
+ if used + cells > width:
+ break
+ result += character
+ used += cells
+ return result + ' ' * (width - used)
+
+
+class NetworkPage:
+ def __init__(self, screen, first_use=False, live=False):
+ self.screen, self.first_use, self.live = screen, first_use, live
+ self.networks, self.wired, self.selected, self.message = [], [], 0, ''
+ screen.keypad(True)
+ screen.timeout(800)
+ try:
+ curses.curs_set(0)
+ except curses.error:
+ pass
+
+ def line(self, row, text, selected=False):
+ height, width = self.screen.getmaxyx()
+ if 0 <= row < height - 1 and width > 3:
+ self.screen.addnstr(row, self.left, fit(text, self.width), self.width,
+ curses.A_REVERSE if selected else curses.A_NORMAL)
+
+ def begin(self):
+ self.screen.erase()
+ height, width = self.screen.getmaxyx()
+ self.width = max(1, min(64, width - 4))
+ self.left = max(0, (width - self.width) // 2)
+ for row, text in enumerate(WORDMARK):
+ self.line(row + 1, text.center(self.width))
+ self.line(4, 'Welcome to Harness' if self.first_use else 'Connect to Wi-Fi')
+ self.line(5, 'Connect to Wi-Fi to get started.' if self.first_use else 'Choose a network.')
+ return height
+
+ def refresh(self):
+ self.begin()
+ self.line(8, 'Finding Wi-Fi…')
+ self.screen.refresh()
+ self.message = ''
+ try:
+ nmcli('radio', 'wifi', 'on', wait=3)
+ self.networks, self.wired = scan(), wired_devices()
+ except (OSError, subprocess.TimeoutExpired, ValueError) as error:
+ self.message = str(error) if isinstance(error, ValueError) else 'Wi-Fi is unavailable. Choose Rescan to try again.'
+ self.selected = 0
+
+ def busy(self, name):
+ self.begin()
+ self.line(8, 'Connecting to ' + clean(name) + '…')
+ self.screen.refresh()
+
+ def password(self, network):
+ value, error = '', ''
+ while True:
+ height = self.begin()
+ self.line(8, clean(network['ssid']))
+ self.line(10, 'Password ' + '*' * min(len(value), self.width - 11))
+ self.line(12, error)
+ self.line(14, 'Connect'.center(self.width), True)
+ try:
+ curses.curs_set(1)
+ if height > 11:
+ self.screen.move(10, self.left + min(10 + len(value), self.width - 1))
+ except curses.error:
+ pass
+ self.screen.refresh()
+ try:
+ key = self.screen.get_wch()
+ except curses.error:
+ continue
+ if key in ('\x1b', '\x03'):
+ return False
+ if key in ('\n', '\r', curses.KEY_ENTER):
+ self.busy(network['ssid'])
+ try:
+ if connect(network, value):
+ return True
+ error = 'Could not connect. Check the password and try again.'
+ except (OSError, subprocess.TimeoutExpired, ValueError) as failure:
+ error = str(failure) if isinstance(failure, ValueError) else 'Connection timed out. Try again.'
+ value = ''
+ elif key in ('\x7f', '\b', curses.KEY_BACKSPACE):
+ value = value[:-1]
+ elif key == '\x15':
+ value = ''
+ elif isinstance(key, str) and key.isprintable() and len(value) < 256:
+ value += key
+
+ def run(self):
+ if self.first_use and connected():
+ return 0
+ self.refresh()
+ checked = time.monotonic()
+ while True:
+ if self.first_use and time.monotonic() - checked >= 2:
+ if connected():
+ return 0
+ checked = time.monotonic()
+ rows = [('wifi', network) for network in self.networks] + [('rescan', None)]
+ rows += [('wired', device) for device in self.wired]
+ if self.first_use:
+ rows += [('install' if self.live else 'offline', None)]
+ self.selected = min(self.selected, len(rows) - 1)
+ height = self.begin()
+ try:
+ curses.curs_set(0)
+ except curses.error:
+ pass
+ # Keep the offline route visible even in a crowded Wi-Fi scan.
+ listed = rows[:-1] if self.first_use else rows
+ visible = max(1, height - (13 if self.first_use else 11))
+ offset = max(0, min(self.selected, len(listed) - 1) - visible + 1)
+ for index, (kind, value) in enumerate(listed[offset:offset + visible], start=offset):
+ if kind == 'wifi':
+ label = value['ssid'] + (' Connected' if value['active'] else f" {value['signal']}%")
+ elif kind == 'wired':
+ label = 'Ethernet ' + value[0]
+ else:
+ label = {'rescan': 'Rescan', 'install': 'Install without connecting', 'offline': 'Continue offline'}[kind]
+ self.line(8 + index - offset, label, index == self.selected)
+ if self.first_use:
+ self.line(height - 4, 'Install without connecting' if self.live else 'Continue offline',
+ self.selected == len(rows) - 1)
+ self.line(height - 2, self.message or ('' if self.networks else 'No Wi-Fi networks found. Rescan or use Ethernet.'))
+ self.screen.refresh()
+ try:
+ key = self.screen.get_wch()
+ except curses.error:
+ continue
+ if key in ('\x1b', '\x03') and not self.first_use:
+ return 1
+ if key in (curses.KEY_UP, curses.KEY_BTAB):
+ self.selected = (self.selected - 1) % len(rows)
+ elif key in (curses.KEY_DOWN, '\t'):
+ self.selected = (self.selected + 1) % len(rows)
+ elif key in ('r', 'R'):
+ self.refresh()
+ elif key in ('i', 'I') and self.first_use and self.live:
+ return INSTALL
+ elif key in ('\n', '\r', curses.KEY_ENTER):
+ kind, value = rows[self.selected]
+ if kind in ('install', 'offline'):
+ return INSTALL if kind == 'install' else OFFLINE
+ if kind == 'rescan':
+ self.refresh()
+ continue
+ self.busy(value['ssid'] if kind == 'wifi' else 'Ethernet')
+ try:
+ if kind == 'wired':
+ if nmcli('device', 'connect', value[0], wait=30).returncode == 0:
+ return 0
+ self.message = 'Could not connect Ethernet. Check the cable and try again.'
+ elif value['active'] or connect(value):
+ return 0
+ elif value['security'] and value['security'] != '--':
+ if self.password(value):
+ return 0
+ else:
+ self.message = 'Could not connect. Choose Rescan and try again.'
+ except (OSError, subprocess.TimeoutExpired, ValueError) as error:
+ self.message = str(error) if isinstance(error, ValueError) else 'Could not connect. Choose Rescan and try again.'
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--first-use', action='store_true')
+ args = parser.parse_args()
+ if os.geteuid() != 0:
+ parser.error('Open Wi-Fi through Harness.')
+ curses.set_escdelay(25)
+ def page(screen):
+ # Treat Ctrl+C as a key, so first use cannot be killed into an empty
+ # workspace. Ordinary Wi-Fi and the password field still handle it as
+ # their existing Back action. wrapper restores the terminal on exit.
+ curses.raw()
+ return NetworkPage(screen, args.first_use, Path('/etc/harness-live').exists()).run()
+ return curses.wrapper(page)
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/os/onboarding.py b/os/onboarding.py
index 397787f7d..8e5ab3e98 100644
--- a/os/onboarding.py
+++ b/os/onboarding.py
@@ -1,92 +1,40 @@
#!/usr/bin/env python3
-"""The USB's short network step; the real agent owns the workspace afterwards."""
-import curses
+"""Open network setup directly, then give the workspace to the real agent."""
import os
from pathlib import Path
import subprocess
-import time
-
-WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
-
-
-def connected():
- try:
- result = subprocess.run(['nmcli', '-t', '-f', 'STATE', 'general'],
- capture_output=True, text=True, timeout=3,
- env=dict(os.environ, LC_ALL='C'))
- return result.returncode == 0 and result.stdout.strip() == 'connected'
- except (OSError, subprocess.TimeoutExpired):
- return False
-
-
-def network_step(screen, error=None):
- screen.keypad(True)
- screen.timeout(1000)
- try:
- curses.curs_set(0)
- except curses.error:
- pass
- selected, checked = 0, 0.0
- while True:
- if time.monotonic() - checked >= 3:
- if connected():
- return 'ready'
- checked = time.monotonic()
- screen.erase()
- height, width = screen.getmaxyx()
- lines = [*WORDMARK, '', 'Connect to start with an agent.', '',
- '[ Connect to Wi-Fi ]', '', '[ Install without connecting ]']
- if error:
- lines += ['', error]
- top = max(0, (height - len(lines)) // 2)
- for index, text in enumerate(lines):
- row = top + index
- if row >= height - 1 or width < 2:
- continue
- attr = curses.A_REVERSE if index == (5 if selected == 0 else 7) else curses.A_BOLD if index < 2 else curses.A_NORMAL
- screen.addnstr(row, max(0, (width - len(text)) // 2), text, max(0, width - 1), attr)
- screen.refresh()
- try:
- key = screen.get_wch()
- except curses.error:
- continue
- if key in ('\t', curses.KEY_BTAB, curses.KEY_UP, curses.KEY_DOWN):
- selected = 1 - selected
- elif key in ('\n', '\r', curses.KEY_ENTER):
- return 'wifi' if selected == 0 else 'install'
- elif key in ('i', 'I'):
- return 'install'
- elif key in ('w', 'W'):
- return 'wifi'
def welcome():
- # No model call, download or account is required to reach the install action.
- if not Path('/etc/harness-live').is_file():
- raise SystemExit('The USB welcome is only available when running from the Harness USB.')
- curses.set_escdelay(25)
- error = None
- while not connected():
- action = curses.wrapper(network_step, error) if error else curses.wrapper(network_step)
- error = None
- if action == 'wifi':
- subprocess.run(['/usr/bin/hn-os', 'wifi'], check=False)
- elif action == 'install':
+ live = Path('/etc/harness-live').is_file()
+ offline = False
+ while True:
+ # The network page advances as soon as connected. The live account can
+ # run it without an administrator password.
+ result = subprocess.run(['sudo', '/usr/bin/python3', '/usr/lib/harness-os/network.py', '--first-use'])
+ if result.returncode == 0:
+ break
+ if result.returncode == 11 and not live:
+ offline = True
+ break
+ if result.returncode == 10 and live:
try:
subprocess.run(['hn', 'os-action', 'install'], check=True, timeout=15)
- except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
- error = 'Could not open Install. Try again, or press Super+i.'
- # The installer owns another tab. Keep this network step available
- # when the user cancels installation and returns to the trial.
+ except (OSError, subprocess.SubprocessError):
+ print('Could not open Install Harness. Press Super+i to try again.')
+ input('Press Enter to return to Wi-Fi.')
continue
+ raise SystemExit('Could not open Wi-Fi. Press Super+w to try again, or Super+t for a terminal.')
pane = os.environ.get('TMUX_PANE', '')
- # The introduction is optional; an IPC hiccup must not prevent the agent
- # from opening. The USB dock and OS shortcuts remain available regardless.
try:
- subprocess.run(['hn', 'os-action', 'ready', pane], check=False, timeout=15)
+ result = subprocess.run(['hn', 'os-action', 'ready', pane], check=False, timeout=15)
+ if result.returncode == 0 and not live:
+ state = Path.home() / '.local/state/harness-os'
+ state.mkdir(parents=True, exist_ok=True)
+ (state / 'onboarded').touch()
except (OSError, subprocess.TimeoutExpired):
pass
- os.execv('/usr/bin/hn-os', ['hn-os', 'try'])
+ os.execv('/usr/bin/hn-os', ['hn-os', 'try', *(['--offline'] if offline else [])])
if __name__ == '__main__':
diff --git a/os/projects.py b/os/projects.py
new file mode 100644
index 000000000..77a197264
--- /dev/null
+++ b/os/projects.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+"""Prepare the OS project root and reserve a per-agent folder without collisions."""
+import argparse
+from datetime import datetime
+from pathlib import Path
+import re
+import unicodedata
+
+
+def prepare(home=None):
+ home = Path.home() if home is None else Path(home)
+ root, legacy = home / 'projects', home / 'Projects'
+ # Keep old terminal/session paths working after the capitalization change.
+ # Two existing directories are never silently merged or replaced.
+ if not root.exists() and not root.is_symlink() and legacy.is_dir() and not legacy.is_symlink():
+ legacy.rename(root)
+ legacy.symlink_to('projects', target_is_directory=True)
+ root.mkdir(parents=True, exist_ok=True)
+ return root
+
+
+def new_project(label='opencode', home=None, at=None):
+ root = prepare(home)
+ at = at or datetime.now()
+ # Match cli/src/lib/agentNames.ts: label-date-time; seconds on collision.
+ label = re.sub(r'[^a-z0-9]+', '-', unicodedata.normalize('NFKD', label).lower()).strip('-') or 'harness'
+ minute, precise = label + at.strftime('-%Y-%m-%d-%H-%M'), label + at.strftime('-%Y-%m-%d-%H-%M-%S')
+ attempt = 0
+ while True:
+ name = minute if attempt == 0 else precise if attempt == 1 else f'{precise}-{attempt}'
+ folder = root / name
+ try:
+ folder.mkdir()
+ return folder
+ except FileExistsError:
+ attempt += 1
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('action', choices=['prepare', 'new'])
+ parser.add_argument('label', nargs='?', default='opencode')
+ args = parser.parse_args()
+ print(new_project(args.label) if args.action == 'new' else prepare())
diff --git a/os/root/etc/skel/.config/opencode/AGENTS.md b/os/root/etc/skel/.config/opencode/AGENTS.md
index e77ebdc65..b9048db78 100644
--- a/os/root/etc/skel/.config/opencode/AGENTS.md
+++ b/os/root/etc/skel/.config/opencode/AGENTS.md
@@ -10,4 +10,4 @@ of guessing from general terminal or desktop conventions.
If asked to install, read that guide and open the native installer with
`harness install`. Disk selection and passwords belong in its local form, never
-in this conversation. Saved USB trial projects belong under `~/Projects`.
+in this conversation. Saved USB trial projects belong under `~/projects`.
diff --git a/os/root/etc/skel/Projects/AGENTS.md b/os/root/etc/skel/projects/AGENTS.md
similarity index 100%
rename from os/root/etc/skel/Projects/AGENTS.md
rename to os/root/etc/skel/projects/AGENTS.md
diff --git a/os/root/etc/sudoers.d/20-harness-network b/os/root/etc/sudoers.d/20-harness-network
new file mode 100644
index 000000000..02a10a58b
--- /dev/null
+++ b/os/root/etc/sudoers.d/20-harness-network
@@ -0,0 +1,3 @@
+# 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
diff --git a/os/root/usr/bin/hn b/os/root/usr/bin/hn
index ea022fd6d..14a0dbdee 100644
--- a/os/root/usr/bin/hn
+++ b/os/root/usr/bin/hn
@@ -7,6 +7,11 @@ export HARNESS_CLI_ARGS='[]'
# This computer's working tabs must survive an update without a cloud account or
# network. hn's ordinary local sessions retain their complete pane references.
export HARNESS_TUI_DESK=off
+if [ ! -f "$HOME/.local/state/harness-os/onboarded" ]; then
+ export HARNESS_OS_FIRST_USE=1
+else
+ unset HARNESS_OS_FIRST_USE
+fi
if [ -f /etc/harness-live ]; then
export HARNESS_OS_LIVE=1
export HARNESS_TUI_TMUX_CONF=/usr/share/harness-os/tmux-live.conf
diff --git a/os/root/usr/lib/harness-os/session b/os/root/usr/lib/harness-os/session
index 6a181d3fe..8a2bba97e 100644
--- a/os/root/usr/lib/harness-os/session
+++ b/os/root/usr/lib/harness-os/session
@@ -16,7 +16,8 @@ export HARNESS_TUI_TMUX_CONF=/usr/share/harness-os/tmux.conf
if [ -z "${WLR_RENDERER:-}" ] && /usr/lib/harness-os/virtio-2d; then
export WLR_RENDERER=pixman
fi
-mkdir -p "$HOME/.local/bin" "$HOME/Projects" "$HOME/.local/state/harness-os"
+mkdir -p "$HOME/.local/bin" "$HOME/.local/state/harness-os"
+/usr/bin/python3 /usr/lib/harness-os/projects.py prepare >/dev/null
# Use the systemd user's existing bus so activation and the compositor share one
# environment. A second dbus-run-session bus would split those services.
export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"
@@ -39,7 +40,7 @@ trap - EXIT
systemctl --user stop harness-os.target || true
systemctl --user start harness-daemon.service || true
printf '%s\n' 'Graphics unavailable; continuing in hn on the console.'
-cd "$HOME/Projects"
+cd "$HOME/projects"
while :; do
/usr/bin/hn || true
sleep 2
diff --git a/os/root/usr/lib/systemd/user/hn-screen.service b/os/root/usr/lib/systemd/user/hn-screen.service
index 70b52defc..888664069 100644
--- a/os/root/usr/lib/systemd/user/hn-screen.service
+++ b/os/root/usr/lib/systemd/user/hn-screen.service
@@ -16,7 +16,8 @@ Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin
Environment=npm_config_prefix=%h/.local
Environment=HARNESS_OS=1
Environment=BROWSER=hn-browser
-WorkingDirectory=%h/Projects
+ExecStartPre=/usr/bin/python3 /usr/lib/harness-os/projects.py prepare
+WorkingDirectory=-%h/projects
ExecStart=/usr/bin/foot --config=/usr/share/harness-os/foot.ini /usr/bin/hn
Restart=always
RestartSec=1
diff --git a/os/root/usr/share/harness-os/guide.md b/os/root/usr/share/harness-os/guide.md
index fe28cef07..ff2071fcb 100644
--- a/os/root/usr/share/harness-os/guide.md
+++ b/os/root/usr/share/harness-os/guide.md
@@ -32,15 +32,15 @@ in every answer or interrupt useful work with installation reminders.
If the user asks to install, run `harness install` without sudo or arguments.
It opens the real installer in Harness and returns to the conversation. The user
-chooses Disk, Encryption, Password and Repeat password, then selects Install.
+chooses Disk, Encryption, Password and Repeat password, then selects Install Harness.
Encryption starts enabled. The account is `me` and the computer is `harness`.
-Installation erases the selected disk; the form says so beside its Install action.
+Installation erases the entire selected disk. Explain this when discussing installation.
Never ask for disk/password details in chat, guess a target disk, or construct an
unattended install configuration. Never type the user's password for them.
Installation works offline. Do not require a model, account or network to install.
USB work is temporary until saved elsewhere or installed. Create trial projects
-under `~/Projects` so the installer can carry their files into the installed home.
+under `~/projects` so the installer can carry their files into the installed home.
This does not preserve running processes. Keep API keys in the agent's normal
credential storage, outside projects; do not put secrets in example source files.
@@ -113,7 +113,7 @@ conversation history. Describe only collaboration controls present in this TUI.
## OS keys and essentials
- Super+i opens Install on the live USB. The persistent Install button does too.
- F10 focuses the USB dock; Tab moves between its buttons and Enter activates one.
+ F10 focuses Install Harness in the footer; Enter opens installation.
- Super+w opens Wi-Fi. Ethernet connects automatically when available.
- Super+n opens New Harness; Super+t opens a terminal; Super+m connects a computer.
- Super+b switches between Harness and the browser. Super+Enter focuses Harness.
diff --git a/os/root/usr/share/harness-os/tmux-live.conf b/os/root/usr/share/harness-os/tmux-live.conf
index ef097967f..f9eee4380 100644
--- a/os/root/usr/share/harness-os/tmux-live.conf
+++ b/os/root/usr/share/harness-os/tmux-live.conf
@@ -2,3 +2,7 @@
source-file /usr/share/harness-os/tmux.conf
unbind U
bind I os-action install
+
+# Share the window list's row; only this button owns the install click target.
+set -g status-right '#{?#{e|>=:#{client_width},80},Make Harness your OS. ,}#[range=user|os-install bold][ Install Harness ]#[norange]'
+set -g status-right-length 48
diff --git a/os/root/usr/share/harness-os/tmux.conf b/os/root/usr/share/harness-os/tmux.conf
index 1e5d40728..9822e586f 100644
--- a/os/root/usr/share/harness-os/tmux.conf
+++ b/os/root/usr/share/harness-os/tmux.conf
@@ -4,7 +4,7 @@ unbind D
unbind C-z
bind W os-action wifi
bind U new-window -n Updates '/usr/bin/harness updates'
-set -g status-right '#{@harness-update} "#H" %H:%M'
+set -g status-right '#{@harness-update}'
set -g status-right-length 60
set -g @hn-animations off
set -g exit-empty off
diff --git a/os/tests/build-update-fixture.py b/os/tests/build-update-fixture.py
index ab1131ca4..fcf1c5ed2 100644
--- a/os/tests/build-update-fixture.py
+++ b/os/tests/build-update-fixture.py
@@ -38,10 +38,13 @@ def ref(name):
data = (output / name).read_bytes()
return {'url': base_url + name, 'sha256': hashlib.sha256(data).hexdigest(), 'size': len(data)}
+baseline = json.loads((runtime / 'source.json').read_text())['release_baselines']['cli']['version']
documents = {
'hn.json': {'version': fixture_version, 'builds': {'linux-x64': ref('harness-tui')}},
'cli.json': {'cli': {'version': fixture_version, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
'cli-current.json': {'cli': {'version': current_cli, 'cli': ref('cli-current.mjs'), 'notify': ref('notify.mjs')}},
+ 'cli-ancestor.json': {'cli': {'version': baseline, 'cli': ref('cli.mjs'), 'notify': ref('notify.mjs')}},
+ 'feeds-ancestor.json': {'cli': base_url + 'cli-ancestor.json'},
'feeds-hn.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli-current.json'},
'feeds-both.json': {'hn': base_url + 'hn.json', 'cli': base_url + 'cli.json'},
}
diff --git a/os/tests/compression_vm.py b/os/tests/compression_vm.py
index 69942b1d2..29741a404 100644
--- a/os/tests/compression_vm.py
+++ b/os/tests/compression_vm.py
@@ -81,9 +81,9 @@ def run_trial(iso, folder, firmware):
vm.command('nmcli networking off')
# Check the recompressed media's actual payload checksum in the guest.
vm.command('cd /run/archiso/bootmnt/arch/x86_64 && sha512sum -c airootfs.sha512', timeout=90)
- vm.command(user('sh -c ' + shlex.quote('mkdir -p "$HOME/Projects/compression"; printf %s ' +
+ vm.command(user('sh -c ' + shlex.quote('mkdir -p "$HOME/projects/compression"; printf %s ' +
shlex.quote(base64.b64encode(project).decode()) +
- ' | base64 -d > "$HOME/Projects/compression/retained.txt"')))
+ ' | base64 -d > "$HOME/projects/compression/retained.txt"')))
for name, data in [('config.json', json.dumps(config).encode()),
('probe.py', INSTALL_PROBE.encode())]:
encoded = base64.b64encode(data).decode()
@@ -116,7 +116,7 @@ def run_trial(iso, folder, firmware):
if config['encrypt']:
result['unlock_prompt_seconds'] = vm.unlock_prompt_seconds
result['keyboard'] = check_graphical_keyboard(vm, 'compression')
- assert vm.read_file('/home/me/Projects/compression/retained.txt') == project
+ assert vm.read_file('/home/me/projects/compression/retained.txt') == project
vm.command('test ! -e /etc/harness-live && ! pgrep -x chromium && ! pgrep -x opencode')
# A new disk/boot per trial prevents page-cache reuse inside the guest.
vm.command('sleep 20; hn-os measure > /tmp/compression-idle.json', timeout=35)
diff --git a/os/tests/development.sh b/os/tests/development.sh
index 110d29aba..f63703434 100644
--- a/os/tests/development.sh
+++ b/os/tests/development.sh
@@ -2,9 +2,9 @@
# Run in a fresh installed VM's hn pane after installing gcc/make on demand.
set -euo pipefail
REPORT_DIR="$HOME/.local/state/harness-os/development-check"
-mkdir -p "$REPORT_DIR" "$HOME/Projects/os-validation"
+mkdir -p "$REPORT_DIR" "$HOME/projects/os-validation"
trap 'printf "%s\n" "$?" > "$REPORT_DIR/status"' EXIT
-cd "$HOME/Projects/os-validation"
+cd "$HOME/projects/os-validation"
git init -q
cat > main.c <<'C'
#include <stdio.h>
diff --git a/os/tests/dsh/run.sh b/os/tests/dsh/run.sh
index 34aa8d6d6..85f664eb6 100644
--- a/os/tests/dsh/run.sh
+++ b/os/tests/dsh/run.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
INPUTS=$(cd -- "$(dirname -- "$0")" && pwd)
-ROOT="$HOME/Projects/os-dsh"
+ROOT="$HOME/projects/os-dsh"
REPORT="$HOME/.local/state/harness-os/dsh-check"
mkdir -p "$REPORT" "$ROOT/qa"
trap 'printf "%s\n" "$?" > "$REPORT/status"' EXIT
diff --git a/os/tests/essentials_vm.py b/os/tests/essentials_vm.py
index 49fd355f6..76f41e9b5 100644
--- a/os/tests/essentials_vm.py
+++ b/os/tests/essentials_vm.py
@@ -71,10 +71,18 @@ exit 1
def wait_screen(vm, words, name, timeout=20):
deadline = time.monotonic() + timeout
while True:
- text = screen_text(vm, name)
+ # OCR drops dark text inside the selected network's light highlight.
+ # Read the real focused terminal for input readiness, and retain its
+ # actual framebuffer separately for visual inspection.
+ vm.command(USER_ENV + 'hn capture-pane -p > /tmp/harness-wifi-screen.txt')
+ content = vm.read_file('/tmp/harness-wifi-screen.txt')
+ (vm.folder / (name + '.txt')).write_bytes(content)
+ text = ' '.join(content.decode().lower().split())
if all(word.lower() in text for word in words):
+ vm.screenshot(name)
return text
if time.monotonic() >= deadline:
+ vm.screenshot(name)
raise AssertionError('Expected screen text not rendered: ' + repr(words) + '; saw: ' + text)
time.sleep(.25)
@@ -90,45 +98,57 @@ def wireless(vm, result):
vm.command("nmcli -t -f DEVICE,TYPE device | awk -F: '$2 == \"ethernet\" {print $1}' > /run/harness-ethernet; "
'while read -r dev; do nmcli device disconnect "$dev"; nmcli device set "$dev" managed no; done < /run/harness-ethernet')
vm.command('! ip route show default | grep -v "dev $(cat /run/harness-station)"')
- vm.command(USER_ENV + 'hn new-window -n Wi-Fi ' + shlex.quote('hn-os wifi'))
- wait_screen(vm, ['harness-test'], 'wifi-01-networks')
- # nmtui lists saved Ethernet profiles even when their device is unmanaged.
- # The first row is Wired connection 1; select the scanned wireless row.
- vm.keys('down')
+ form = 'sudo python3 /usr/lib/harness-os/network.py --first-use; result=$?; printf %s "$result" > /tmp/wifi-form-result; exec bash -l'
+ vm.command(USER_ENV + 'hn new-window -n Wi-Fi ' + shlex.quote(form))
+ wait_screen(vm, ['harness-test', 'install without connecting'], 'wifi-01-networks')
+ vm.keys('esc')
+ wait_screen(vm, ['harness-test'], 'wifi-01-escape-keeps-welcome')
+ vm.keys('ctrl', 'c')
+ wait_screen(vm, ['harness-test'], 'wifi-01-interrupt-keeps-welcome')
+ # Wi-Fi is the first selection. A bad password stays recoverable in-page.
vm.keys('ret')
wait_screen(vm, ['password'], 'wifi-02-password')
+ vm.type_probe('wrong-wifi-password')
+ vm.keys('ret')
+ wait_screen(vm, ['check the password'], 'wifi-02-password-retry', timeout=50)
+ vm.keys('esc')
+ vm.keys('r')
+ wait_screen(vm, ['harness-test'], 'wifi-02-rescan')
+ vm.keys('ret')
+ wait_screen(vm, ['password'], 'wifi-02-password-again')
vm.type_probe(PASSWORD)
text = screen_text(vm, 'wifi-03-password-masked')
assert PASSWORD not in text, 'Wi-Fi password was visible in the form'
vm.keys('ret')
- vm.command('for n in $(seq 1 40); do '
- 'if nmcli -t -f GENERAL.STATE device show "$(cat /run/harness-station)" | grep -q "100"; then exit 0; fi; '
- 'sleep .5; done; exit 1', timeout=30)
+ vm.command('for n in $(seq 1 80); do test -s /tmp/wifi-form-result && '
+ 'test "$(cat /tmp/wifi-form-result)" = 0 && exit 0; sleep .5; done; exit 1', timeout=45)
# A real HTTP response and DNS lookup through the radio, not a mocked state.
output, _ = vm.command('ip route; resolvectl query harness.test; '
'test "$(curl --noproxy "*" -fsS --max-time 10 http://harness.test:8080)" = harness-wifi-success')
(vm.folder / 'wifi-route-and-dns.txt').write_text(output)
vm.screenshot('wifi-04-connected')
- vm.keys('esc')
vm.command(USER_ENV + 'hn list-panes -a -F "#{pane_current_command}"')
- result['checks'].append('Actual hn Wi-Fi screen scans a simulated radio, masks WPA2 password, connects with DHCP and resolves/fetches HTTP over wireless with Ethernet disconnected')
+ result['checks'].append('Fullscreen Wi-Fi welcome puts Wi-Fi first, retries a wrong masked password, rescans, and advances automatically after DHCP and resolves/fetches HTTP over wireless with Ethernet disconnected')
+ # Restart NetworkManager too: a radio toggle alone could reuse an in-memory
+ # secret instead of proving the entered password was saved to disk.
+ vm.monitor('set_link', name='hnnet', up=False)
+ vm.command('systemctl restart NetworkManager; nm-online -q --timeout=40', timeout=45)
# Connection must survive a radio toggle, without another password prompt.
vm.command('nmcli radio wifi off; sleep 1; nmcli radio wifi on; '
'for n in $(seq 1 45); do if curl --noproxy "*" -fsS --max-time 2 http://harness.test:8080 | '
'grep -Fx harness-wifi-success; then exit 0; fi; sleep 1; done; exit 1', timeout=100)
vm.command('find /etc/NetworkManager/system-connections -name "*.nmconnection" -exec stat -c "%a %U %n" {} \\;')
result['checks'].append('Wireless reconnects after a radio off/on cycle using its stored profile')
- # Cancel setup while offline, return to Harness, then reopen it.
+ # The full-page offline action returns an explicit install result; Esc does
+ # not strand a first-time user in an empty shell.
vm.command('nmcli device disconnect "$(cat /run/harness-station)"')
- vm.command(USER_ENV + 'hn new-window -n Try ' + shlex.quote('hn-os try'))
- wait_screen(vm, ['harness-test'], 'wifi-05-trial-offline')
- vm.keys('esc')
- wait_screen(vm, ['connect to wi-fi', 'press enter'], 'wifi-06-cancelled')
- vm.keys('ret')
- vm.command(USER_ENV + 'systemctl --user is-active --quiet hn-screen')
- vm.command('! pgrep -u 1000 -x opencode')
- result['checks'].append('Cancelling offline trial network setup explains how to connect and returns to Harness without launching a disconnected agent')
+ vm.command(USER_ENV + 'hn new-window -n Offline ' + shlex.quote(form.replace('/tmp/wifi-form-result', '/tmp/wifi-offline-result')))
+ wait_screen(vm, ['install without connecting'], 'wifi-05-offline-install')
+ vm.keys('i')
+ vm.command('for n in $(seq 1 40); do test "$(cat /tmp/wifi-offline-result 2>/dev/null)" = 10 && exit 0; sleep .25; done; exit 1')
+ result['checks'].append('First-use Wi-Fi always offers offline installation, and selecting it exits with the native install action')
vm.command('nmcli connection up ' + SSID, timeout=60)
+ vm.monitor('set_link', name='hnnet', up=True)
vm.command('while read -r dev; do nmcli device set "$dev" managed yes; nmcli device connect "$dev"; done < /run/harness-ethernet')
@@ -142,20 +162,24 @@ def sound(vm, result):
match = re.search(r'Volume: ([0-9.]+)([^\r\n]*)', output)
assert match, 'No default audio output'
return float(match.group(1)), '[MUTED]' in match.group(2)
+ def press_volume(key, expected):
+ # labwc starts wpctl asynchronously. Observe completion instead of
+ # assuming it finished within 400 ms during first-agent startup.
+ started = time.monotonic()
+ vm.keys(key)
+ while True:
+ actual = volume()
+ if actual == expected:
+ result.setdefault('audio_key_seconds', {})[key + ('-unmute' if key == 'audiomute' and not expected[1] else '')] = round(time.monotonic() - started, 3)
+ return
+ assert time.monotonic() - started < 5, (key + ' did not reach PipeWire', actual, expected)
+ time.sleep(.1)
vm.command(USER_ENV + 'wpctl set-volume @DEFAULT_AUDIO_SINK@ 0.5')
vm.command(USER_ENV + 'wpctl set-mute @DEFAULT_AUDIO_SINK@ 0')
- vm.keys('volumeup')
- time.sleep(.4)
- assert volume() == (.55, False), ('Volume up did not reach PipeWire', volume())
- vm.keys('volumedown')
- time.sleep(.4)
- assert volume() == (.5, False), ('Volume down did not reach PipeWire', volume())
- vm.keys('audiomute')
- time.sleep(.4)
- assert volume() == (.5, True), ('Mute did not reach PipeWire', volume())
- vm.keys('audiomute')
- time.sleep(.4)
- assert volume() == (.5, False), ('Unmute did not reach PipeWire', volume())
+ press_volume('volumeup', (.55, False))
+ press_volume('volumedown', (.5, False))
+ press_volume('audiomute', (.5, True))
+ press_volume('audiomute', (.5, False))
tone = '''import array, math, wave
with wave.open('/tmp/harness-tone.wav', 'wb') as output:
output.setnchannels(2); output.setsampwidth(2); output.setframerate(48000)
@@ -195,8 +219,8 @@ def main():
vm.command('stty -echo')
vm.command(USER_ENV + '/usr/lib/harness-os/wait-runtime')
vm.command(USER_ENV + 'sh -c ' + shlex.quote('for n in $(seq 1 60); do systemctl --user is-active --quiet hn-screen && pgrep -u 1000 -x foot >/dev/null && exit 0; sleep .25; done; exit 1'))
- sound(vm, result)
wireless(vm, result)
+ sound(vm, result)
vm.stop()
with wave.open(str(folder / 'audio-1.wav'), 'rb') as recording:
samples = array.array('h', recording.readframes(recording.getnframes()))
diff --git a/os/tests/fast_update_vm.py b/os/tests/fast_update_vm.py
index 3ea9066c2..70a42e8d7 100644
--- a/os/tests/fast_update_vm.py
+++ b/os/tests/fast_update_vm.py
@@ -41,12 +41,16 @@ def exercise(vm, fixture, host_url):
vm.command('systemd-run --user --collect --unit=harness-test-feed python3 -m http.server 19447 '
'--bind 127.0.0.1 --directory /tmp/fast-updates')
vm.command('for n in $(seq 1 30); do curl -fsS http://127.0.0.1:19447/fixture.json && exit 0; sleep .2; done; exit 1')
+ # Even though a source CLI reports 0.0.1, an already-included public version
+ # must not replace it. The new 999.x fixture below must still be accepted.
+ vm.command('harness updates check --feeds /tmp/fast-updates/feeds-ancestor.json', timeout=60)
+ vm.command('test ! -e ~/.local/state/harness-os/updates/ready.json && test ! -e ~/.local/state/harness-os/updates/current')
# The radio/network can remain off: only the loopback test release is used.
vm.command('sudo nmcli networking off')
put(vm, '/tmp/update-session-probe.py', PROBE)
vm.command('hn new-window -n update-probe ' + shlex.quote('python3 /tmp/update-session-probe.py'))
- vm.command('for n in $(seq 1 40); do test -s ~/Projects/session-probe/pid && exit 0; sleep .25; done; exit 1')
- vm.command('cp ~/Projects/session-probe/pid /tmp/fast-original-pid; cat /proc/$(cat /tmp/fast-original-pid)/stat > /tmp/fast-original-stat')
+ vm.command('for n in $(seq 1 40); do test -s ~/projects/session-probe/pid && exit 0; sleep .25; done; exit 1')
+ vm.command('cp ~/projects/session-probe/pid /tmp/fast-original-pid; cat /proc/$(cat /tmp/fast-original-pid)/stat > /tmp/fast-original-stat')
vm.command('systemctl --user show harness-daemon -p MainPID --value > /tmp/fast-original-daemon')
vm.command('hn new-window -n live-agent opencode')
vm.command('for n in $(seq 1 80); do pgrep -u 1000 -x opencode > /tmp/fast-original-agent && exit 0; sleep .25; done; exit 1')
@@ -64,7 +68,7 @@ def exercise(vm, fixture, host_url):
'sudo journalctl _UID=1000 _SYSTEMD_USER_UNIT=harness-update.service --no-pager; '
'systemctl --user status harness-update.timer harness-update.service --no-pager; exit 1', timeout=75)
wait_text(vm, 'update ready', 'fast-01-notice', status_bar=True)
- checks = ['User timer discovers, verifies and stages a real hn release without changing the running selection']
+ checks = ['An already-included public CLI release is ignored before staging; independent newer hn and CLI releases remain eligible', 'User timer discovers, verifies and stages a real hn release without changing the running selection']
vm.command('test ! -e ' + state + '/current')
def alive(name):
@@ -72,7 +76,7 @@ def exercise(vm, fixture, host_url):
import time
pid = Path('/tmp/fast-original-pid').read_text().strip()
assert Path('/proc/'+pid+'/stat').read_text().split()[21] == Path('/tmp/fast-original-stat').read_text().split()[21]
-root = Path.home() / 'Projects/session-probe'
+root = Path.home() / 'projects/session-probe'
before = (root/'heartbeat').stat().st_mtime_ns
time.sleep(.6)
assert (root/'heartbeat').stat().st_mtime_ns != before
@@ -85,7 +89,7 @@ assert (root/'heartbeat').stat().st_mtime_ns != before
vm.type_probe(name)
vm.keys('ret')
vm.command('for n in $(seq 1 30); do grep -Fx ' + shlex.quote(name) +
- ' ~/Projects/session-probe/input && exit 0; sleep .1; done; exit 1')
+ ' ~/projects/session-probe/input && exit 0; sleep .1; done; exit 1')
vm.screenshot(name + '-accepted-input')
def activate(expect_failure=False):
diff --git a/os/tests/session_vm.py b/os/tests/session_vm.py
index da8781c80..e0d3f6150 100644
--- a/os/tests/session_vm.py
+++ b/os/tests/session_vm.py
@@ -14,7 +14,7 @@ from vm import VM
PROBE = '''import os, pathlib, sys, threading, time
-root = pathlib.Path.home() / 'Projects/session-probe'
+root = pathlib.Path.home() / 'projects/session-probe'
root.mkdir(exist_ok=True)
(root / 'pid').write_text(str(os.getpid()))
(root / 'input').write_text('')
@@ -80,18 +80,18 @@ def live_lock(vm, user):
def installed_session(vm, config, result):
put(vm, '/tmp/harness-session-probe.py', PROBE)
vm.command('hn new-window -n session-probe ' + shlex.quote('python3 /tmp/harness-session-probe.py'))
- vm.command('for n in $(seq 1 60); do test -s ~/Projects/session-probe/pid && test -s ~/Projects/session-probe/heartbeat && exit 0; sleep 0.25; done; exit 1')
- vm.command('cp ~/Projects/session-probe/pid /tmp/session-original-pid')
+ vm.command('for n in $(seq 1 60); do test -s ~/projects/session-probe/pid && test -s ~/projects/session-probe/heartbeat && exit 0; sleep 0.25; done; exit 1')
+ vm.command('cp ~/projects/session-probe/pid /tmp/session-original-pid')
time.sleep(1)
assert 'visible lock probe' in screen_text(vm, 'session-before-lock'), 'The visible terminal probe was not rendered'
accepted = []
def work_survives():
- vm.command('test "$(cat ~/Projects/session-probe/pid)" = "$(cat /tmp/session-original-pid)" && kill -0 "$(cat /tmp/session-original-pid)"')
- vm.command('before=$(cat ~/Projects/session-probe/heartbeat); sleep 0.5; test "$before" != "$(cat ~/Projects/session-probe/heartbeat)"')
+ vm.command('test "$(cat ~/projects/session-probe/pid)" = "$(cat /tmp/session-original-pid)" && kill -0 "$(cat /tmp/session-original-pid)"')
+ vm.command('before=$(cat ~/projects/session-probe/heartbeat); sleep 0.5; test "$before" != "$(cat ~/projects/session-probe/heartbeat)"')
expected = ''.join(word + '\n' for word in accepted)
expression = ('from pathlib import Path; import time\n'
- 'p = Path.home()/"Projects/session-probe/input"\n'
+ 'p = Path.home()/"projects/session-probe/input"\n'
'expected = ' + repr(expected) + '\n'
'deadline = time.monotonic() + 3\n'
'while p.read_text() != expected and time.monotonic() < deadline: time.sleep(.05)\n'
@@ -282,7 +282,7 @@ def main():
'cat ~/.local/state/harness-os/display.log; ps -eo pid,ppid,sid,comm,args --width 240; '
'cat /sys/class/drm/card*-*/status /sys/class/drm/card*-*/dpms; '
'sudo -n sh -c "cat /sys/kernel/debug/dri/*/state"; '
- 'cat ~/Projects/session-probe/input',
+ 'cat ~/projects/session-probe/input',
check=False, timeout=15)
(folder / 'session-diagnostics.log').write_text(output)
except Exception:
diff --git a/os/tests/test_first_use.py b/os/tests/test_first_use.py
index aa9040bcd..5fe228683 100644
--- a/os/tests/test_first_use.py
+++ b/os/tests/test_first_use.py
@@ -41,10 +41,11 @@ class FirstUse(unittest.TestCase):
def test_connected_machine_starts_bundled_agent_without_model_or_config_override(self):
with tempfile.TemporaryDirectory() as temp, patch.object(hn_os.Path, 'home', return_value=Path(temp)), \
patch.object(hn_os, 'connected', return_value=True), patch.object(hn_os, 'wifi') as wifi, \
- patch.object(hn_os.os, 'chdir') as cwd, patch.object(hn_os.os, 'execv') as execute:
+ patch.object(hn_os.os, 'chdir') as cwd, patch.object(hn_os.os, 'execv') as execute, \
+ patch.object(hn_os.subprocess, 'check_output', return_value=str(Path(temp) / 'projects/opencode-2026-10-04-09-05')):
hn_os.try_harness()
wifi.assert_not_called()
- cwd.assert_called_once_with(Path(temp) / 'Projects')
+ cwd.assert_called_once_with(str(Path(temp) / 'projects/opencode-2026-10-04-09-05'))
execute.assert_called_once_with('/usr/bin/opencode', ['opencode'])
def test_disconnected_or_cancelled_network_setup_never_launches_agent(self):
@@ -61,7 +62,8 @@ class FirstUse(unittest.TestCase):
with tempfile.TemporaryDirectory() as temp, patch.object(hn_os.Path, 'home', return_value=Path(temp)), \
patch.object(hn_os, 'connected', side_effect=[False, True]), \
patch.object(hn_os, 'wifi', return_value=0), patch.object(hn_os.os, 'chdir'), \
- patch.object(hn_os.os, 'execv') as execute:
+ patch.object(hn_os.os, 'execv') as execute, \
+ patch.object(hn_os.subprocess, 'check_output', return_value=str(Path(temp) / 'projects/opencode-2026-10-04-09-05')):
hn_os.try_harness()
execute.assert_called_once_with('/usr/bin/opencode', ['opencode'])
diff --git a/os/tests/test_installer.py b/os/tests/test_installer.py
index 18f382ed2..3387a221f 100644
--- a/os/tests/test_installer.py
+++ b/os/tests/test_installer.py
@@ -353,8 +353,8 @@ class InteractiveInstall(unittest.TestCase):
self.secret = 'test-password-123'
def fill_passwords(self):
- # Disk -> encryption -> password -> repeat -> Install button via Enter.
- self.screen.keys.extend(['\t', '\t', *self.secret, '\n', *self.secret, '\n'])
+ # The safe disk is selected and Password is focused immediately.
+ self.screen.keys.extend([*self.secret, '\n', *self.secret, '\n'])
def confirm(self):
self.screen.keys.append('\n') # Activate Install; no second confirmation screen.
@@ -415,7 +415,7 @@ class InteractiveInstall(unittest.TestCase):
self.assertIn('Encryption [ ]', self.screen.frames[0])
def test_main_form_checkbox_can_disable_encryption(self):
- self.screen.keys.extend(['\t', ' ', '\t', *self.secret, '\n', *self.secret, '\n'])
+ self.screen.keys.extend([installer.curses.KEY_BTAB, ' ', '\t', *self.secret, '\n', *self.secret, '\n'])
self.confirm()
installer.main()
self.assertFalse(self.install.call_args.args[0]['encrypt'])
@@ -430,7 +430,7 @@ class InteractiveInstall(unittest.TestCase):
def test_selecting_another_disk_does_not_start_installation(self):
self.inventory.return_value.append(dict(self.disk, name='/dev/vdb', serial='SECOND_DISK'))
- self.screen.keys.extend(['\n', installer.curses.KEY_DOWN, '\n'])
+ self.screen.keys.extend([installer.curses.KEY_BTAB, installer.curses.KEY_BTAB, '\n', installer.curses.KEY_DOWN, '\n', '\t', '\t'])
self.fill_passwords()
self.confirm()
installer.main()
@@ -446,7 +446,7 @@ class InteractiveInstall(unittest.TestCase):
def test_long_disk_model_keeps_size_and_device_visible_on_a_small_screen(self):
self.screen.size = (18, 54)
self.disk['model'] = 'A very long manufacturer and model name' * 3
- self.screen.keys.extend(['\n', '\n'])
+ self.screen.keys.extend([installer.curses.KEY_BTAB, installer.curses.KEY_BTAB, '\n', '\n', '\t', '\t'])
self.fill_passwords()
self.confirm()
installer.main()
@@ -459,14 +459,14 @@ class InteractiveInstall(unittest.TestCase):
def test_escaping_disk_picker_preserves_original_selection(self):
self.inventory.return_value.append(dict(self.disk, name='/dev/vdb', serial='SECOND_DISK'))
- self.screen.keys.extend(['\n', installer.curses.KEY_DOWN, '\x1b'])
+ self.screen.keys.extend([installer.curses.KEY_BTAB, installer.curses.KEY_BTAB, '\n', installer.curses.KEY_DOWN, '\x1b', '\t', '\t'])
self.fill_passwords()
self.confirm()
installer.main()
self.assertEqual(self.install.call_args.args[0]['disk'], '/dev/vda')
def test_password_mismatch_can_be_corrected_without_restarting(self):
- self.screen.keys.extend(['\t', '\t', *self.secret, '\n', *'different', '\n', '\n', installer.curses.KEY_BTAB, '\x15', *self.secret, '\n'])
+ self.screen.keys.extend([*self.secret, '\n', *'different', '\n', '\n', installer.curses.KEY_BTAB, '\x15', *self.secret, '\n'])
self.confirm()
installer.main()
self.assertTrue(any('Passwords do not match.' in frame for frame in self.screen.frames))
@@ -474,7 +474,7 @@ class InteractiveInstall(unittest.TestCase):
def test_live_usb_is_excluded_from_picker(self):
self.inventory.return_value.insert(0, dict(self.disk, name='/dev/sda', mountpoints=['/run/archiso/bootmnt']))
- self.screen.keys.extend(['\n', '\n'])
+ self.screen.keys.extend([installer.curses.KEY_BTAB, installer.curses.KEY_BTAB, '\n', '\n', '\t', '\t'])
self.fill_passwords()
self.confirm()
installer.main()
diff --git a/os/tests/test_live_update.py b/os/tests/test_live_update.py
index d28cb034d..8c94b3638 100644
--- a/os/tests/test_live_update.py
+++ b/os/tests/test_live_update.py
@@ -75,6 +75,23 @@ class FastUpdates(unittest.TestCase):
self.assertEqual(update.prepared(), target)
self.assertEqual(len(list((self.state / 'builds').iterdir())), 1)
+ def test_public_release_already_included_in_os_source_cannot_replace_newer_fixes(self):
+ self.base.write_text(json.dumps({'source_commit': 'source-built',
+ 'release_baselines': {'cli': {'version': '1.1.0', 'commit': 'a' * 40}}}))
+ with self.feed():
+ self.assertTrue(update.check())
+ # The independent TUI update still arrives; the older public CLI does not.
+ ready = update.verify(update.prepared())
+ self.assertEqual(ready['versions'], {'hn': '1.1.0', 'cli': '1.0.0'})
+ self.assertEqual((update.prepared() / 'cli.mjs').read_bytes(), b'old cli.mjs')
+ self.assertEqual((update.prepared() / 'notify.mjs').read_bytes(), b'old notify.mjs')
+
+ def test_release_newer_than_the_os_source_baseline_is_still_downloaded(self):
+ self.base.write_text(json.dumps({'release_baselines': {'cli': {'version': '1.0.5', 'commit': 'a' * 40}}}))
+ with self.feed():
+ self.assertTrue(update.check())
+ self.assertEqual(update.verify(update.prepared())['versions']['cli'], '1.1.0')
+
def test_bad_cli_hook_does_not_stage_half_a_pair_or_block_independent_hn(self):
with self.feed(fail='notify.mjs'):
self.assertTrue(update.check())
diff --git a/os/tests/test_network.py b/os/tests/test_network.py
new file mode 100644
index 000000000..6d6b764c1
--- /dev/null
+++ b/os/tests/test_network.py
@@ -0,0 +1,117 @@
+import curses
+import importlib.util
+from pathlib import Path
+import subprocess
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('network', Path(__file__).resolve().parents[1] / 'network.py')
+network = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(network)
+
+
+def result(code=0, output=''):
+ return subprocess.CompletedProcess([], code, output, '')
+
+
+WIFI = dict(ssid='a:network', device='wlan0', security='WPA2', active=False, signal=88)
+
+
+class Screen:
+ def __init__(self, keys):
+ self.keys, self.lines = iter(keys), []
+ def keypad(self, value): pass
+ def timeout(self, value): pass
+ def refresh(self): pass
+ def erase(self): pass
+ def move(self, *args): pass
+ def getmaxyx(self): return 24, 80
+ def get_wch(self): return next(self.keys)
+ def addnstr(self, row, column, text, width, style): self.lines.append((row, text.rstrip()))
+
+
+class Network(unittest.TestCase):
+ 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')
+ self.assertEqual(run.call_args.args[0][0], '/usr/bin/nmcli')
+
+ def test_scans_escape_ssids_and_deduplicate_radios_without_hiding_open_networks(self):
+ rows = 'a\\:network:60:WPA2:wlan0:aa\\:bb:\nopen:90:--:wlan0:bb\\:cc:\na\\:network:88:WPA2:wlan0:cc\\:dd:*\n:80:WPA2:wlan0:dd\\:ee:\n'
+ with patch.object(network, 'nmcli', return_value=result(output=rows)):
+ found = network.scan()
+ self.assertEqual([n['ssid'] for n in found], ['a:network', 'open'])
+ self.assertEqual(found[0]['signal'], 88)
+ self.assertEqual(found[0]['bssid'], 'cc:dd')
+
+ def test_password_is_only_passed_on_stdin_and_only_success_enables_reconnect(self):
+ calls = []
+ def run(*args, **kwargs):
+ calls.append((args, kwargs))
+ return result()
+ with patch.object(network, 'nmcli', side_effect=run):
+ self.assertTrue(network.connect(WIFI, 'secret:with spaces'))
+ self.assertNotIn('secret:with spaces', repr([args for args, _ in calls]))
+ self.assertEqual(calls[1][1]['secret'], '802-11-wireless-security.psk:secret:with spaces\n')
+ self.assertEqual(calls[-1][0][-2:], ('connection.autoconnect', 'yes'))
+ self.assertFalse(any('delete' in args for args, _ in calls))
+
+ def test_bad_password_deletes_only_the_profile_created_by_that_attempt(self):
+ with patch.object(network, 'nmcli', side_effect=[result(), result(4), result()]) as command:
+ self.assertFalse(network.connect(WIFI, 'wrong-password'))
+ identity = command.call_args_list[0].args[command.call_args_list[0].args.index('connection.uuid') + 1]
+ self.assertEqual(command.call_args_list[-1].args, ('connection', 'delete', 'uuid', identity))
+
+ def test_saved_profile_reconnect_does_not_replace_or_delete_it(self):
+ with patch.object(network, 'saved_connection', return_value='existing'), \
+ patch.object(network, 'nmcli', return_value=result(4)) as command:
+ self.assertFalse(network.connect(WIFI))
+ self.assertEqual(command.call_count, 1)
+ self.assertEqual(command.call_args.args, ('connection', 'up', 'uuid', 'existing', 'ifname', 'wlan0'))
+
+ def page(self, keys, live=True):
+ screen = Screen(keys)
+ self.enterContext(patch.object(network.curses, 'curs_set'))
+ self.enterContext(patch.object(network, 'connected', return_value=False))
+ self.enterContext(patch.object(network, 'scan', return_value=[WIFI]))
+ self.enterContext(patch.object(network, 'wired_devices', return_value=[['eth0', 'ethernet', 'disconnected']]))
+ self.enterContext(patch.object(network, 'nmcli', return_value=result()))
+ return screen, network.NetworkPage(screen, first_use=True, live=live)
+
+ def test_first_page_has_wifi_above_wired_rescan_and_always_visible_offline_install(self):
+ screen, page = self.page(['\x1b', '\x03', 'r', 'i'])
+ self.assertEqual(page.run(), network.INSTALL)
+ text = '\n'.join(text for _, text in screen.lines)
+ self.assertIn('Welcome to Harness', text)
+ self.assertLess(text.index('a:network'), text.index('Ethernet'))
+ self.assertIn('Rescan', text)
+ self.assertIn('Install without connecting', text)
+ self.assertNotIn('Quit', text)
+ self.assertNotIn('Activate', text)
+
+ def test_password_retry_is_masked_and_success_advances_without_quit(self):
+ screen, page = self.page(['\n', *'wrong-password', '\n', *'right-password', '\n'])
+ with patch.object(network, 'connect', side_effect=[False, False, True]):
+ self.assertEqual(page.run(), 0)
+ text = '\n'.join(text for _, text in screen.lines)
+ self.assertIn('Check the password', text)
+ self.assertNotIn('wrong-password', text)
+ self.assertNotIn('right-password', text)
+ self.assertIn('*****', text)
+
+ def test_working_ethernet_skips_the_form(self):
+ screen, page = self.page([])
+ with patch.object(network, 'connected', return_value=True), patch.object(network, 'scan') as scan:
+ self.assertEqual(page.run(), 0)
+ scan.assert_not_called()
+
+ def test_open_network_failure_does_not_ask_for_a_nonexistent_password(self):
+ screen, page = self.page(['\n', 'i'])
+ with patch.object(network, 'scan', return_value=[dict(WIFI, security='--')]), \
+ patch.object(network, 'connect', return_value=False), patch.object(page, 'password') as password:
+ self.assertEqual(page.run(), network.INSTALL)
+ password.assert_not_called()
+
+ 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 ')
diff --git a/os/tests/test_onboarding.py b/os/tests/test_onboarding.py
index 928ceb52d..d0ab25a26 100644
--- a/os/tests/test_onboarding.py
+++ b/os/tests/test_onboarding.py
@@ -2,6 +2,7 @@ import importlib.util
import os
from pathlib import Path
import subprocess
+import tempfile
import unittest
from unittest.mock import patch
@@ -10,67 +11,59 @@ onboarding = importlib.util.module_from_spec(spec)
spec.loader.exec_module(onboarding)
+def result(code=0):
+ return subprocess.CompletedProcess([], code)
+
+
class Onboarding(unittest.TestCase):
- def test_ethernet_skips_network_form_and_starts_the_real_agent(self):
- with patch.object(onboarding.Path, 'is_file', return_value=True), \
- patch.object(onboarding, 'connected', return_value=True), \
- patch.object(onboarding.curses, 'set_escdelay'), \
- patch.object(onboarding.curses, 'wrapper') as form, \
- patch.object(onboarding.subprocess, 'run') as command, \
- patch.object(onboarding.os, 'execv') as execute, \
- patch.dict(os.environ, {'TMUX_PANE': '%4'}):
- onboarding.welcome()
- form.assert_not_called()
- command.assert_called_once_with(['hn', 'os-action', 'ready', '%4'], check=False, timeout=15)
- execute.assert_called_once_with('/usr/bin/hn-os', ['hn-os', 'try'])
+ def test_network_page_opens_directly_then_agent_and_workspace_start(self):
+ for live in [True, False]:
+ with self.subTest(live=live), tempfile.TemporaryDirectory() as temp, \
+ patch.object(onboarding.Path, 'is_file', return_value=live), \
+ patch.object(onboarding.Path, 'home', return_value=Path(temp)), \
+ patch.object(onboarding.subprocess, 'run', return_value=result()) as command, \
+ patch.object(onboarding.os, 'execv') as execute, \
+ patch.dict(os.environ, {'TMUX_PANE': '%4'}):
+ onboarding.welcome()
+ self.assertEqual(command.call_args_list[0].args[0],
+ ['sudo', '/usr/bin/python3', '/usr/lib/harness-os/network.py', '--first-use'])
+ self.assertEqual(command.call_args_list[1].args[0], ['hn', 'os-action', 'ready', '%4'])
+ execute.assert_called_once_with('/usr/bin/hn-os', ['hn-os', 'try'])
+ self.assertEqual((Path(temp) / '.local/state/harness-os/onboarded').exists(), not live)
- def test_offline_install_opens_native_form_without_starting_an_agent(self):
+ def test_offline_install_opens_native_form_and_returns_to_network_page(self):
with patch.object(onboarding.Path, 'is_file', return_value=True), \
- patch.object(onboarding, 'connected', return_value=False), \
- patch.object(onboarding.curses, 'set_escdelay'), \
- patch.object(onboarding.curses, 'wrapper', side_effect=['install', KeyboardInterrupt]), \
- patch.object(onboarding.subprocess, 'run') as command, \
+ patch.object(onboarding.subprocess, 'run', side_effect=[result(10), result(), KeyboardInterrupt]) as command, \
patch.object(onboarding.os, 'execv') as execute:
with self.assertRaises(KeyboardInterrupt):
onboarding.welcome()
- command.assert_called_once_with(['hn', 'os-action', 'install'], check=True, timeout=15)
+ self.assertEqual(command.call_args_list[1].args[0], ['hn', 'os-action', 'install'])
+ self.assertEqual(command.call_args_list[0], command.call_args_list[2])
execute.assert_not_called()
- def test_cancelled_wifi_returns_to_network_form(self):
- with patch.object(onboarding.Path, 'is_file', return_value=True), \
- patch.object(onboarding, 'connected', return_value=False), \
- patch.object(onboarding.curses, 'set_escdelay'), \
- patch.object(onboarding.curses, 'wrapper', side_effect=['wifi', KeyboardInterrupt]) as form, \
- patch.object(onboarding.subprocess, 'run') as command, \
+ def test_installed_system_can_open_workspace_offline(self):
+ with tempfile.TemporaryDirectory() as temp, patch.object(onboarding.Path, 'is_file', return_value=False), \
+ patch.object(onboarding.Path, 'home', return_value=Path(temp)), \
+ patch.object(onboarding.subprocess, 'run', side_effect=[result(11), result()]), \
patch.object(onboarding.os, 'execv') as execute:
- with self.assertRaises(KeyboardInterrupt):
- onboarding.welcome()
- self.assertEqual(form.call_count, 2)
- command.assert_called_once_with(['/usr/bin/hn-os', 'wifi'], check=False)
- execute.assert_not_called()
+ onboarding.welcome()
+ execute.assert_called_once_with('/usr/bin/hn-os', ['hn-os', 'try', '--offline'])
- def test_network_failure_stays_recoverable_and_installed_system_rejects_usb_flow(self):
- for failure in [OSError('missing'), subprocess.TimeoutExpired('nmcli', 3)]:
- with patch.object(onboarding.subprocess, 'run', side_effect=failure):
- self.assertFalse(onboarding.connected())
- with patch.object(onboarding.Path, 'is_file', return_value=False), \
- patch.object(onboarding, 'connected') as connected:
- with self.assertRaises(SystemExit):
- onboarding.welcome()
- connected.assert_not_called()
+ def test_failed_layout_request_does_not_mark_first_use_complete(self):
+ with tempfile.TemporaryDirectory() as temp, patch.object(onboarding.Path, 'is_file', return_value=False), \
+ patch.object(onboarding.Path, 'home', return_value=Path(temp)), \
+ patch.object(onboarding.subprocess, 'run', side_effect=[result(), subprocess.TimeoutExpired('hn', 15)]), \
+ patch.object(onboarding.os, 'execv') as execute:
+ onboarding.welcome()
+ self.assertFalse((Path(temp) / '.local/state/harness-os/onboarded').exists())
+ execute.assert_called_once()
- def test_install_launch_failure_keeps_a_recoverable_network_screen(self):
+ def test_install_launch_failure_keeps_network_recoverable(self):
with patch.object(onboarding.Path, 'is_file', return_value=True), \
- patch.object(onboarding, 'connected', return_value=False), \
- patch.object(onboarding.curses, 'set_escdelay'), \
- patch.object(onboarding.curses, 'wrapper', side_effect=['install', KeyboardInterrupt]) as form, \
- patch.object(onboarding.subprocess, 'run', side_effect=subprocess.TimeoutExpired('hn', 15)), \
- patch.object(onboarding.os, 'execv') as execute:
+ patch.object(onboarding.subprocess, 'run', side_effect=[result(10), subprocess.TimeoutExpired('hn', 15), KeyboardInterrupt]) as command, \
+ patch('builtins.input') as acknowledge, patch.object(onboarding.os, 'execv') as execute:
with self.assertRaises(KeyboardInterrupt):
onboarding.welcome()
- self.assertIn('Could not open Install', form.call_args.args[1])
+ acknowledge.assert_called_once()
+ self.assertEqual(command.call_args_list[0], command.call_args_list[2])
execute.assert_not_called()
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/os/tests/test_projects.py b/os/tests/test_projects.py
new file mode 100644
index 000000000..f5783ba1b
--- /dev/null
+++ b/os/tests/test_projects.py
@@ -0,0 +1,46 @@
+import importlib.util
+from datetime import datetime
+from pathlib import Path
+import tempfile
+import unittest
+
+spec = importlib.util.spec_from_file_location('projects', Path(__file__).resolve().parents[1] / 'projects.py')
+projects = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(projects)
+
+
+class Projects(unittest.TestCase):
+ def test_agent_folders_match_cli_convention_and_never_reuse_work(self):
+ with tempfile.TemporaryDirectory() as temp:
+ now = datetime(2026, 10, 4, 9, 5, 7)
+ folders = [projects.new_project('OpenCode', temp, now) for _ in range(3)]
+ self.assertEqual([path.name for path in folders], ['opencode-2026-10-04-09-05',
+ 'opencode-2026-10-04-09-05-07', 'opencode-2026-10-04-09-05-07-2'])
+ self.assertTrue(all(path.parent == Path(temp) / 'projects' and path.is_dir() for path in folders))
+
+ def test_legacy_capitalization_keeps_old_session_paths_working(self):
+ with tempfile.TemporaryDirectory() as temp:
+ home = Path(temp)
+ legacy = home / 'Projects'
+ legacy.mkdir()
+ (legacy / 'keep.txt').write_text('my work')
+ if (home / 'projects').exists():
+ self.skipTest('Case-sensitive migration needs a Linux filesystem')
+ root = projects.prepare(home)
+ self.assertEqual((root / 'keep.txt').read_text(), 'my work')
+ self.assertTrue(legacy.is_symlink())
+ self.assertEqual((legacy / 'keep.txt').read_text(), 'my work')
+ self.assertEqual(projects.prepare(home), root)
+
+ def test_two_existing_directories_are_not_merged_or_overwritten(self):
+ with tempfile.TemporaryDirectory() as temp:
+ home = Path(temp)
+ root = projects.prepare(home)
+ if (home / 'Projects').exists():
+ self.skipTest('Case-sensitive migration needs a Linux filesystem')
+ (root / 'same.txt').write_text('new work')
+ (home / 'Projects').mkdir()
+ (home / 'Projects/same.txt').write_text('old work')
+ projects.prepare(home)
+ self.assertEqual((root / 'same.txt').read_text(), 'new work')
+ self.assertEqual((home / 'Projects/same.txt').read_text(), 'old work')
diff --git a/os/tests/test_runtime_baseline.py b/os/tests/test_runtime_baseline.py
new file mode 100644
index 000000000..79ec5c482
--- /dev/null
+++ b/os/tests/test_runtime_baseline.py
@@ -0,0 +1,41 @@
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+spec = importlib.util.spec_from_file_location('baseline', Path(__file__).parents[1] / 'tools/runtime-baseline.py')
+baseline = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(baseline)
+
+
+class RuntimeBaseline(unittest.TestCase):
+ def test_only_ancestor_release_tags_constrain_updates_and_versions_sort_numerically(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ def git(*args):
+ return subprocess.check_output(['git', '-C', str(root), '-c', 'user.name=Fixture',
+ '-c', '[email protected]', *args],
+ text=True, stderr=subprocess.DEVNULL).strip()
+ git('init', '-b', 'main')
+ git('commit', '--allow-empty', '-m', 'first')
+ git('tag', 'v0.3.9_cli')
+ git('commit', '--allow-empty', '-m', 'published')
+ published = git('rev-parse', 'HEAD')
+ git('tag', 'v0.3.57_cli')
+ git('tag', 'v0.1.12_tui')
+ git('tag', 'v900.0_cli') # Not a release version.
+ git('checkout', '-b', 'other')
+ git('commit', '--allow-empty', '-m', 'not in the OS')
+ git('tag', 'v1.0.0_cli')
+ git('checkout', 'main')
+ git('commit', '--allow-empty', '-m', 'unreleased OpenCode compatibility fix')
+ self.assertEqual(baseline.baselines(root), {
+ 'cli': {'version': '0.3.57', 'commit': published},
+ 'hn': {'version': '0.1.12', 'commit': published},
+ })
+ # An incomplete checkout must fail instead of silently allowing a downgrade.
+ (root / '.git/shallow').write_text(git('rev-parse', 'HEAD') + '\n')
+ with self.assertRaisesRegex(ValueError, 'full Git history'):
+ baseline.baselines(root)
diff --git a/os/tests/test_trial_projects.py b/os/tests/test_trial_projects.py
index 07b142515..2f34ba4f1 100644
--- a/os/tests/test_trial_projects.py
+++ b/os/tests/test_trial_projects.py
@@ -15,7 +15,7 @@ class TrialProjects(unittest.TestCase):
def test_saved_project_tree_keeps_git_binary_data_permissions_and_links(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
- source, target = base / 'Projects', base / 'installed'
+ source, target = base / 'projects', base / 'installed'
(source / 'game/.git').mkdir(parents=True)
(source / 'empty').mkdir()
script = source / 'game/run'
@@ -41,7 +41,7 @@ class TrialProjects(unittest.TestCase):
def test_external_links_are_preserved_without_copying_their_contents(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
- source, outside = base / 'Projects', base / 'outside'
+ source, outside = base / 'projects', base / 'outside'
source.mkdir()
outside.mkdir()
(outside / 'secret').write_text('outside project')
@@ -54,7 +54,7 @@ class TrialProjects(unittest.TestCase):
def test_special_files_fail_preflight_and_copy_without_hanging(self):
with tempfile.TemporaryDirectory() as temp:
- source = Path(temp) / 'Projects'
+ source = Path(temp) / 'projects'
source.mkdir()
os.mkfifo(source / 'pipe')
with self.assertRaisesRegex(ValueError, 'special file'):
diff --git a/os/tests/update_guest.py b/os/tests/update_guest.py
index 011b76fa3..950c63d16 100644
--- a/os/tests/update_guest.py
+++ b/os/tests/update_guest.py
@@ -32,7 +32,7 @@ def main():
original_version = version()
original_runtime = Path('/usr/share/harness-os/runtime.json').read_text()
project = Path.home() / 'Projects/update-survivor'
- project.mkdir()
+ project.mkdir(parents=True, exist_ok=True)
(project / 'keep.txt').write_text('keep this project through apply, restart and rollback\n')
(project / 'heartbeat.py').write_text('''import os, pathlib, time
root = pathlib.Path.home() / 'Projects/update-survivor'
@@ -100,6 +100,8 @@ while True:
alive()
receipt['checks'].append('Repeated apply recognizes the installed build without another transaction')
restart()
+ assert (Path.home() / 'projects/update-survivor/keep.txt').read_text() == (project / 'keep.txt').read_text()
+ receipt['checks'].append('Legacy Projects migrates to lowercase projects while existing session paths remain valid')
receipt['checks'].append('The same terminal process and project survive restarting both Harness daemon and screen')
for name, info in manifest['runtime']['files'].items():
path = Path('/usr/lib/harness') / name
diff --git a/os/tests/vm.py b/os/tests/vm.py
index b34b47bb1..33bfe6181 100644
--- a/os/tests/vm.py
+++ b/os/tests/vm.py
@@ -412,18 +412,19 @@ def check_first_use(vm, user, folder):
defaults = json.loads(vm.read_file('/home/me/.config/opencode/opencode.json'))
assert not set(defaults) & {'model', 'provider', 'providers'}, 'The image must retain upstream model and provider defaults'
assert defaults.get('update') == 'disable', 'The packaged agent must remain managed by system updates'
- vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "Connect to start with an agent" && exit 0; sleep 1; done; exit 1')), timeout=40)
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "Connect to Wi-Fi to get started" && exit 0; sleep 1; done; exit 1')), timeout=40)
vm.screenshot('01a-network-first')
- vm.keys('ret')
- vm.command('for n in $(seq 1 30); do pgrep -x "nmtui|nmtui-connect" >/dev/null && exit 0; sleep 1; done; exit 1', timeout=40)
vm.command('! pgrep -u 1000 -x opencode')
- vm.screenshot('01a-try-needs-network')
+ # Escape cannot leave a first-use dead end. Offline install is in this page.
+ vm.keys('esc')
+ vm.command(user('hn capture-pane -p') + ' | grep -q "Install without connecting"')
+ vm.keys('i')
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "Repeat password" && exit 0; sleep 1; done; exit 1')), timeout=40)
+ vm.screenshot('01a-offline-install')
vm.keys('esc')
- vm.command('for n in $(seq 1 15); do ! pgrep -x "nmtui|nmtui-connect" >/dev/null && exit 0; sleep 1; done; exit 1', timeout=20)
- vm.command('sleep 1; ! pgrep -u 1000 -x opencode')
# The OS shortcut needs neither a prefix nor Shift, and works offline.
vm.keys('meta_l', 'i')
- vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "All data on this disk will be erased" && exit 0; sleep 1; done; exit 1')), timeout=40)
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "Repeat password" && exit 0; sleep 1; done; exit 1')), timeout=40)
vm.screenshot('01b-direct-install-offline')
vm.keys('esc')
vm.command('sleep 1; test "$(lsblk -n -o TYPE /dev/vda | wc -l)" -eq 1')
@@ -468,10 +469,45 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shell
vm.command('for n in $(seq 1 90); do pgrep -u 1000 -x opencode >/dev/null && exit 0; sleep 1; done; exit 1', timeout=100)
time.sleep(5)
vm.screenshot('01d-bundled-opencode')
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do test "$(hn list-panes -F "#{pane_id}" | wc -l)" -eq 3 && break; sleep .5; done; hn list-panes -F "#{pane_id}|#{pane_left}|#{pane_top}|#{pane_width}|#{pane_height}" > /tmp/hn-first-panes.txt')))
+ # Serial shell-integration escapes precede the first output line. Read exact
+ # file bytes so the first pane is not silently discarded by an anchored regex.
+ pane_data = vm.read_file('/tmp/hn-first-panes.txt')
+ (folder / 'first-use-panes.txt').write_bytes(pane_data)
+ pane_rows = [line.split('|') for line in pane_data.decode().splitlines() if re.match(r'^%\d+\|', line)]
+ assert len(pane_rows) == 3, 'First use must contain three real terminal panes'
+ left = min(pane_rows, key=lambda row: int(row[1]))
+ right = sorted((row for row in pane_rows if row != left), key=lambda row: int(row[2]))
+ # Coordinates describe the terminal cells inside hn's one-cell pane border.
+ assert int(left[1]) == 1 and right[0][1] == right[1][1] and int(right[1][2]) > int(right[0][2])
+ assert abs(int(left[3]) - int(right[0][3])) <= 2, 'First-use columns must be balanced'
+ assert abs(int(right[0][4]) - int(right[1][4])) <= 2, 'Right terminals must split their column equally'
+ # hn's pane_pid describes remote panes; these local panes are backed by
+ # tmux. Ask that actual backend for the agent PID, then inspect /proc.
+ # The session's original shell path can lag discovery after exec.
+ vm.command(user('tmux list-panes -a -F "#{pane_pid}|#{pane_current_command}"') + ' > /tmp/hn-first-processes.txt')
+ process_data = vm.read_file('/tmp/hn-first-processes.txt')
+ (folder / 'first-use-processes.txt').write_bytes(process_data)
+ agent_pids = [line.split('|')[0] for line in process_data.decode().splitlines()
+ if re.fullmatch(r'\d+\|opencode', line)]
+ assert len(agent_pids) == 1, 'The trial must have exactly one visible OpenCode process'
+ vm.command('readlink /proc/' + agent_pids[0] + '/cwd > /tmp/hn-first-agent-path.txt')
+ agent_path = vm.read_file('/tmp/hn-first-agent-path.txt').decode().strip()
+ assert re.fullmatch(r'/home/me/projects/opencode-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}(?:-\d+)*', agent_path), agent_path
+ vm.command(user('hn display-message -p "#{E:status-right}"') + ' > /tmp/hn-first-footer.txt')
+ footer = vm.read_file('/tmp/hn-first-footer.txt').decode()
+ assert 'Make Harness your OS.' in footer and '[ Install Harness ]' in footer, footer
+ for index, row in enumerate(right):
+ vm.command(user('hn select-pane -t ' + row[0]))
+ vm.type_probe('echo starter-terminal-' + str(index))
+ vm.keys('ret')
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -Fx starter-terminal-' + str(index) + ' && exit 0; sleep .2; done; exit 1')))
+ vm.command(user('hn select-pane -t ' + left[0]))
+ vm.screenshot('01d-three-real-panes')
# runuser changes the account but retains the serial root shell's cwd.
# OpenCode 2 resolves a project through its service; /root is inaccessible
# to me. Inspect the same project as the visible agent instead.
- vm.command(user('sh -c ' + shlex.quote('cd "$HOME/Projects" && /usr/bin/opencode debug config > /tmp/hn-opencode-config.json')), timeout=60)
+ vm.command(user('sh -c ' + shlex.quote('cd "$HOME/projects" && /usr/bin/opencode debug config > /tmp/hn-opencode-config.json')), timeout=60)
config_sources = vm.read_file('/tmp/hn-opencode-config.json')
(folder / 'opencode-config-sources.json').write_bytes(config_sources)
# V2 reports configuration sources, not the resolved V1 object. Its
@@ -513,12 +549,12 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shell
# F10 reaches the dock without consuming the agent's ordinary Tab key.
vm.keys('f10')
vm.keys('ret')
- vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "All data on this disk will be erased" && exit 0; sleep 1; done; exit 1')), timeout=40)
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "Repeat password" && exit 0; sleep 1; done; exit 1')), timeout=40)
vm.screenshot('01d-dock-install')
vm.keys('esc')
time.sleep(1)
vm.click_word('01d-mouse-install', 'Install')
- vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "All data on this disk will be erased" && exit 0; sleep 1; done; exit 1')), timeout=40)
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "Repeat password" && exit 0; sleep 1; done; exit 1')), timeout=40)
vm.command('test "$(lsblk -n -o TYPE /dev/vda | wc -l)" -eq 1')
vm.keys('esc')
# Exercise what a first-time user actually does after choosing Try: type
@@ -545,24 +581,27 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shell
(folder / 'first-agent-guide.txt').write_bytes(vm.read_file('/tmp/hn-first-guide.txt'))
vm.screenshot('01f-agent-explains-harness')
assert guide_status == 0, 'Bundled OpenCode must explain the actual OS shortcuts from its local guide'
- vm.type_probe('create a folder named usb-trial in the current folder and an index html page inside it saying hello harness')
+ # Build inside the actual per-agent project, as a person does. A sibling
+ # directory would instead exercise OpenCode's external-directory permission.
+ trial_project = agent_path + '/usb-trial/index.html'
+ vm.type_probe('create the folder usb-trial in this project and an index html page inside it saying hello harness')
vm.keys('ret')
- vm.command('for n in $(seq 1 120); do test -s /home/me/Projects/usb-trial/index.html && '
- 'grep -iq "hello harness" /home/me/Projects/usb-trial/index.html && exit 0; sleep 1; done; exit 1', timeout=140)
- (folder / 'trial-project.html').write_bytes(vm.read_file('/home/me/Projects/usb-trial/index.html'))
+ vm.command('for n in $(seq 1 120); do test -s ' + shlex.quote(trial_project) + ' && '
+ 'grep -iq "hello harness" ' + shlex.quote(trial_project) + ' && exit 0; sleep 1; done; exit 1', timeout=140)
+ (folder / 'trial-project.html').write_bytes(vm.read_file(trial_project))
vm.screenshot('01g-agent-created-trial-project')
# Test the agent-led install entry too. It may open the form; it must never
# choose a disk or perform the destructive action from the conversation.
vm.type_probe('open the harness installer for me but do not choose a disk or start installation')
vm.keys('ret')
- vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 90); do hn capture-pane -p | grep -q "All data on this disk will be erased" && exit 0; sleep 1; done; exit 1')), timeout=100)
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 90); do hn capture-pane -p | grep -q "Repeat password" && exit 0; sleep 1; done; exit 1')), timeout=100)
vm.command('test "$(lsblk -n -o TYPE /dev/vda | wc -l)" -eq 1')
vm.screenshot('01h-agent-opened-installer')
vm.keys('esc')
# No model flag/config, API key, account, or installer. Validate a real
# upstream-default reply; preserve all events rather than just the exit code.
prompt = 'What is six times seven? Reply with only the decimal number. Do not use tools.'
- command = 'cd "$HOME/Projects" && timeout 120 /usr/bin/opencode run --format json ' + shlex.quote(prompt) + ' > /tmp/hn-first-chat.jsonl 2>/tmp/hn-first-chat.err'
+ command = 'cd "$HOME/projects" && timeout 120 /usr/bin/opencode run --format json ' + shlex.quote(prompt) + ' > /tmp/hn-first-chat.jsonl 2>/tmp/hn-first-chat.err'
_, status = vm.command(user('sh -c ' + shlex.quote(command)), timeout=140, check=False)
raw = vm.read_file('/tmp/hn-first-chat.jsonl')
errors = vm.read_file('/tmp/hn-first-chat.err')
@@ -587,6 +626,7 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shell
vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 60); do '
'hn list-panes -a -F "#{pane_id}" | grep -Fx ' + shlex.quote(agent_pane.group(1)) +
' >/dev/null || exit 0; sleep .25; done; exit 1')), timeout=20)
+ return trial_project
def install_interactively(vm, config, folder):
@@ -637,17 +677,24 @@ if status:
return output
try:
- wait_screen('All data on this disk will be erased')
+ wait_screen('Repeat password')
vm.screenshot('install-01-form')
+ # A first typed character must go straight into the masked password.
+ vm.type_probe('x')
+ entered = wait_screen('Repeat password')
+ assert '[*' in entered, 'Installer did not initially focus Password'
+ vm.keys('ctrl', 'u')
+ vm.keys('shift', 'tab')
+ vm.keys('shift', 'tab')
vm.keys('ret')
wait_screen('Select disk')
vm.screenshot('install-02-disks')
vm.keys('esc')
- wait_screen('All data on this disk will be erased')
+ wait_screen('Repeat password')
vm.keys('ret')
wait_screen('Select disk')
vm.keys('ret')
- wait_screen('All data on this disk will be erased')
+ wait_screen('Repeat password')
vm.keys('tab')
if not config['encrypt']:
vm.keys('spc')
@@ -656,14 +703,15 @@ if status:
vm.keys('ret')
vm.type_probe(config['password'])
vm.keys('ret')
- output = wait_screen('All data on this disk will be erased')
+ output = wait_screen('Repeat password')
assert config['password'] not in output and '*' * len(config['password']) in output, 'Password fields must be masked'
vm.screenshot('install-03-ready')
# Finishing password entry only focuses Install. No disk has changed yet.
vm.command('test "$(lsblk -n -o TYPE /dev/vda | wc -l)" -eq 1')
vm.keys('ret')
if progress_status == 0:
- wait_screen('Installing Harness', timeout=30)
+ progress = wait_screen('Preparing the disk|Setting up encryption|Copying Harness|Setting up your account', timeout=30)
+ assert 'Keep this computer powered on' not in progress and 'Installing Harness' not in progress
vm.screenshot('install-04-progress')
wait_screen('Harness is installed', timeout=900)
vm.screenshot('install-05-complete')
@@ -794,7 +842,7 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'
vm.screenshot('01-live-hn')
output, _ = vm.command(user('hn-os measure'))
(folder / 'live-measurement.txt').write_text(output)
- check_first_use(vm, user, folder)
+ trial_project = check_first_use(vm, user, folder)
result['checks'].append('USB opens network setup; Super+i opens Install offline; Super+t opens a terminal without a setup form')
result['checks'].append('Installer errors remain visible until acknowledged; exiting a direct terminal removes its pane')
result['checks'].append('USB first agent conversation accepts physical keyboard input and displays the expected reply')
@@ -844,7 +892,7 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'
username='me', hostname='harness', password='test-password-123',
encrypt=args.encrypt, serial_console=True)
# Installation must work with the NIC down, using the ISO's immutable payload.
- (folder / 'trial-project.html').write_bytes(vm.read_file('/home/me/Projects/usb-trial/index.html'))
+ (folder / 'trial-project.html').write_bytes(vm.read_file(trial_project))
vm.command(user('sh -c ' + shlex.quote('mkdir -p "$HOME/.config"; printf trial-only > "$HOME/.config/hn-trial-credential"')))
vm.command('nmcli networking off')
install_interactively(vm, config, folder)
@@ -864,11 +912,17 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'
vm.start(live=False)
unlock_delay = 100 if config['encrypt'] else 0
vm.login_installed(config, unlock_delay=unlock_delay)
- saved_trial = vm.read_file('/home/me/Projects/usb-trial/index.html')
+ vm.command('for n in $(seq 1 60); do test -f ~/.local/state/harness-os/onboarded && '
+ 'test "$(hn list-panes -F "#{pane_id}" | wc -l)" -eq 3 && exit 0; sleep .5; done; exit 1', timeout=40)
+ vm.screenshot('installed-first-workspace')
+ vm.command('hn capture-pane -p | grep -qv "Enter.*Start OpenCode"; test -d ~/projects')
+ result['checks'].append('Fresh installed first boot opens the same three real panes and records onboarding only once')
+ saved_trial = vm.read_file(trial_project)
assert saved_trial == (folder / 'trial-project.html').read_bytes(), 'The installed home lost or changed the agent-created trial project'
- vm.command('test ! -e /home/me/.config/hn-trial-credential && test "$(stat -c %u /home/me/Projects/usb-trial/index.html)" -eq 1000')
+ vm.command('test ! -e /home/me/.config/hn-trial-credential && test "$(stat -c %u ' + shlex.quote(trial_project) + ')" -eq 1000')
transfer = json.loads(vm.read_file('/home/me/.local/state/harness-os/trial-projects.json'))
- assert transfer['entries']['usb-trial/index.html']['sha256'] == hashlib.sha256(saved_trial).hexdigest()
+ relative_trial = str(Path(trial_project).relative_to('/home/me/projects'))
+ assert transfer['entries'][relative_trial]['sha256'] == hashlib.sha256(saved_trial).hexdigest()
result['checks'].append('Agent-created USB trial project survives offline installation and installed boot byte-for-byte')
result['deliberate_unlock_delay_seconds'] = unlock_delay
if unlock_delay:
@@ -936,7 +990,7 @@ pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
checkpoint = re.search(r'Checkpoint ([A-Za-z0-9_-]+)', output).group(1)
vm.command('pacman -Q hn-os-recovery-probe && test -f /etc/hn-os-recovery-probe')
result['checks'].append('A real offline package transaction creates its pre-update checkpoint')
- vm.command('printf keep-my-project > ~/Projects/recovery-probe.txt')
+ vm.command('printf keep-my-project > ~/projects/recovery-probe.txt')
vm.command("sudo sh -c 'printf broken > /etc/hn-os-recovery-probe; chmod 000 /usr/lib/harness/harness-tui'")
vm.command('sync')
vm.stop()
@@ -960,7 +1014,7 @@ pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
result['recovered_unlock_prompt_seconds'] = vm.unlock_prompt_seconds
if vm.acceleration == 'kvm':
assert vm.unlock_prompt_seconds < 30, 'Recovered unlock prompt exceeded 30 seconds; see recovered-boot-journal.log'
- vm.command('test ! -e /etc/hn-os-recovery-probe && test -x /usr/lib/harness/harness-tui && test "$(cat ~/Projects/recovery-probe.txt)" = keep-my-project')
+ vm.command('test ! -e /etc/hn-os-recovery-probe && test -x /usr/lib/harness/harness-tui && test "$(cat ~/projects/recovery-probe.txt)" = keep-my-project')
vm.command('test ! -e /var/lib/pacman/db.lck && ! pacman -Q hn-os-recovery-probe')
result['recovered_keyboard_readiness'] = check_graphical_keyboard(vm, 'recovered')
result['checks'].append('Recovered graphical hn accepts physical-keyboard shell input, returns output and returns home after closing the pane')
@@ -975,7 +1029,7 @@ pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
vm.command('hn new-window -n development ' + shlex.quote('bash /tmp/hn-os-development.sh > "$HOME/.local/state/harness-os/development.log" 2>&1'))
output, _ = vm.command('for n in $(seq 1 60); do test -s ~/.local/state/harness-os/development-check/status && break; sleep 1; done; cat ~/.local/state/harness-os/development.log; test "$(cat ~/.local/state/harness-os/development-check/status)" = 0', timeout=75)
(folder / 'development.log').write_text(output)
- vm.command('hn new-window -n local-preview ' + shlex.quote('node "$HOME/Projects/os-validation/server.mjs"'))
+ vm.command('hn new-window -n local-preview ' + shlex.quote('node "$HOME/projects/os-validation/server.mjs"'))
vm.command('curl --fail --retry 15 --retry-connrefused --retry-delay 1 http://127.0.0.1:18781 | grep -F "Local development works."', timeout=30)
vm.command('hn-browser http://127.0.0.1:18781')
time.sleep(5)
@@ -999,7 +1053,7 @@ pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
with tarfile.open(fileobj=package, mode='w:gz') as archive:
archive.add(Path(__file__).with_name('workloads'), arcname='workloads')
if args.workload_seed:
- seeds = list(args.workload_seed.rglob('Projects/os-workloads'))
+ seeds = list(args.workload_seed.rglob('projects/os-workloads'))
if len(seeds) != 1:
raise RuntimeError('Need exactly one prior generated project tree.')
for name in ['terminal-tool', 'website', 'game', 'fullstack']:
@@ -1020,7 +1074,7 @@ pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
(folder / 'workloads.log').write_text(output)
# Keep both successful and failed model output for review; exclude
# install caches and dependencies from the small source archive.
- vm.command('tar --exclude=node_modules --exclude=.git --exclude=__pycache__ -czf /tmp/hn-workloads-results.tgz -C "$HOME" Projects/os-workloads .local/state/harness-os/workloads', timeout=60)
+ vm.command('tar --exclude=node_modules --exclude=.git --exclude=__pycache__ -czf /tmp/hn-workloads-results.tgz -C "$HOME" projects/os-workloads .local/state/harness-os/workloads', timeout=60)
output, _ = vm.command("printf 'HN_WORKLOAD_ARCHIVE='; base64 -w0 /tmp/hn-workloads-results.tgz; printf '\\n'", timeout=120)
packed = base64.b64decode(re.search(r'HN_WORKLOAD_ARCHIVE=([A-Za-z0-9+/=]+)', output).group(1), validate=True)
destination = folder / 'workloads'
@@ -1057,7 +1111,7 @@ pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
vm.command('hn new-window -n dsh-acceptance ' + shlex.quote('bash /tmp/dsh/run.sh > "$HOME/.local/state/harness-os/dsh-check.log" 2>&1'))
output, _ = vm.command('for n in $(seq 1 2700); do test -s ~/.local/state/harness-os/dsh-check/status && break; sleep 1; done; cat ~/.local/state/harness-os/dsh-check.log', timeout=2720)
(folder / 'dsh-check.log').write_text(output)
- vm.command('tar --exclude=node_modules --exclude=.git --exclude=__pycache__ -czf /tmp/hn-dsh-results.tgz -C "$HOME" Projects/os-dsh .local/state/harness-os/dsh-check', timeout=60)
+ vm.command('tar --exclude=node_modules --exclude=.git --exclude=__pycache__ -czf /tmp/hn-dsh-results.tgz -C "$HOME" projects/os-dsh .local/state/harness-os/dsh-check', timeout=60)
output, _ = vm.command("printf 'HN_DSH_ARCHIVE='; base64 -w0 /tmp/hn-dsh-results.tgz; printf '\\n'", timeout=120)
packed = base64.b64decode(re.search(r'HN_DSH_ARCHIVE=([A-Za-z0-9+/=]+)', output).group(1), validate=True)
destination = folder / 'dsh'
diff --git a/os/tests/workloads/run.sh b/os/tests/workloads/run.sh
index 7bae540ea..3878dc134 100644
--- a/os/tests/workloads/run.sh
+++ b/os/tests/workloads/run.sh
@@ -2,7 +2,7 @@
# Opt-in live-model acceptance. These projects and tools never enter the ISO.
set -uo pipefail
INPUTS=$(cd -- "$(dirname -- "$0")" && pwd)
-WORK="$HOME/Projects/os-workloads"
+WORK="$HOME/projects/os-workloads"
REPORT="$HOME/.local/state/harness-os/workloads"
# The disposable guest has no provider credentials. Exercise the bundled
# binary's upstream model choice, just as a clean first launch does.
@@ -20,7 +20,7 @@ for scenario in terminal-tool website game fullstack; do
mkdir -p "$project"
cp "$INPUTS/$scenario.txt" "$project/TASK.txt"
cat > "$project/opencode.json" <<EOF
-{"permission":{"question":"deny","task":"deny","external_directory":{"*":"deny","$HOME/Projects/**":"allow","/tmp/opencode/**":"allow","/usr/share/harness-os/**":"allow"}}}
+{"permission":{"question":"deny","task":"deny","external_directory":{"*":"deny","$HOME/projects/**":"allow","/tmp/opencode/**":"allow","/usr/share/harness-os/**":"allow"}}}
EOF
printf '\nChecking %s with the upstream default model\n' "$scenario"
if [[ -d "$INPUTS/seed" && ( "$scenario" != game || ! -e "$INPUTS/repair-game" ) ]]; then
diff --git a/os/tools/build-package.py b/os/tools/build-package.py
index 07bf3d3ee..46a847218 100644
--- a/os/tools/build-package.py
+++ b/os/tools/build-package.py
@@ -43,6 +43,8 @@ def stage(source, runtime, destination, commit):
'LICENSE': 'usr/share/licenses/harness-os/LICENSE',
'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/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',
'os/runtime_update.py': 'usr/lib/harness-os/runtime_update.py',
@@ -75,6 +77,8 @@ def stage(source, runtime, destination, commit):
path.chmod(0o755)
for name in ['autostart', 'shutdown']:
(destination / 'usr/share/harness-os/labwc' / name).chmod(0o755)
+ for path in (destination / 'etc/sudoers.d').iterdir():
+ path.chmod(0o440)
info.update(mode='source', files={p.name: {'sha256': digest(p), 'bytes': p.stat().st_size}
for p in library.iterdir() if p.is_file() and not p.is_symlink()})
(destination / 'usr/share/harness-os/runtime.json').write_text(json.dumps(info, indent=2) + '\n')
diff --git a/os/tools/build-runtime.sh b/os/tools/build-runtime.sh
index 15913e429..7ef9abcdf 100644
--- a/os/tools/build-runtime.sh
+++ b/os/tools/build-runtime.sh
@@ -4,6 +4,9 @@ set -euo pipefail
REPO_DIR=$(cd -- "$(dirname -- "$0")/../.." && pwd)
[[ $(uname -sm) == 'Linux x86_64' ]] || { echo 'OS runtimes require an x86_64 Linux build host.' >&2; exit 1; }
cd "$REPO_DIR"
+# Check ancestry before the expensive build. A source bundle can contain fixes
+# newer than the public CLI even while package.json retains its development version.
+python3 os/tools/runtime-baseline.py >/dev/null
npm ci --prefix cli --no-audit --no-fund
(cd cli && node build-bundle.mjs)
cargo build --manifest-path tui/Cargo.toml --locked --release --target x86_64-unknown-linux-musl
@@ -23,5 +26,6 @@ expected_cli = json.loads(pathlib.Path('cli/package.json').read_text())['version
assert output('os/work/runtime/harness-tui', '--version').startswith('hn ' + expected_hn + ' ')
assert output('node', 'cli/dist/cli.js', 'version') == expected_cli
data['versions'] = {'hn': expected_hn, 'cli': expected_cli}
+data['release_baselines'] = json.loads(output('python3', 'os/tools/runtime-baseline.py'))
pathlib.Path('os/work/runtime/source.json').write_text(json.dumps(data, indent=2) + '\n')
PY
diff --git a/os/tools/customize-live.sh b/os/tools/customize-live.sh
index dfbf94289..7a5e7cfd4 100644
--- a/os/tools/customize-live.sh
+++ b/os/tools/customize-live.sh
@@ -12,10 +12,11 @@ ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
useradd -m -G wheel,video,audio -s /bin/bash me
passwd -d me
passwd -d root
-mkdir -p /etc/sudoers.d /home/me/Projects /etc/systemd/system/[email protected]
+mkdir -p /etc/sudoers.d /home/me/projects /etc/systemd/system/[email protected]
echo 'me ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/10-live
chmod 440 /etc/sudoers.d/10-live
-chown me:me /home/me/Projects
+visudo -cf /etc/sudoers.d/20-harness-network
+chown me:me /home/me/projects
systemctl enable NetworkManager systemd-resolved systemd-timesyncd [email protected]
systemctl enable harness-keyring.service
# hn-screen starts the daemon after labwc has published the display environment.
diff --git a/os/tools/hn-os b/os/tools/hn-os
index eaedea3c9..da064dcf3 100644
--- a/os/tools/hn-os
+++ b/os/tools/hn-os
@@ -26,10 +26,7 @@ def connected():
def wifi():
- # Reuse NetworkManager's keyboard UI; it owns password entry and storage.
- # Never put a Wi-Fi password in shell arguments, logs, or our own config.
- subprocess.run(['sudo', 'nmcli', 'radio', 'wifi', 'on'], check=False)
- return subprocess.call(['sudo', 'nmtui-connect'])
+ return subprocess.call(['sudo', '/usr/bin/python3', '/usr/lib/harness-os/network.py'])
def opencode_cpu_ready():
@@ -55,23 +52,22 @@ def prepare_opencode_guidance():
pass
-def try_harness():
+def try_harness(offline=False):
if not opencode_cpu_ready():
print('The bundled OpenCode needs a newer CPU (SSE4.2).')
print('Open a terminal to work locally or connect to a remote agent.')
if sys.stdin.isatty():
input('Press Enter to return to Harness.')
return
- if not connected():
+ if not offline and not connected():
if wifi() != 0 or not connected():
print('OpenCode needs an internet connection. Connect to Wi-Fi or plug in Ethernet, then try again.')
if sys.stdin.isatty():
input('Press Enter to return to Harness.')
return
- projects = Path.home() / 'Projects'
- projects.mkdir(exist_ok=True)
+ project = subprocess.check_output(['/usr/bin/python3', '/usr/lib/harness-os/projects.py', 'new', 'opencode'], text=True).strip()
prepare_opencode_guidance()
- os.chdir(projects)
+ os.chdir(project)
os.execv('/usr/bin/opencode', ['opencode'])
@@ -85,10 +81,12 @@ def main():
if command == 'wifi':
raise SystemExit(wifi())
if command == 'try':
- try_harness()
+ try_harness(offline='--offline' in args)
return
if command == 'welcome':
os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/onboarding.py'])
+ if command == 'starter':
+ os.execv('/bin/bash', ['bash', '-l'])
if command == 'hardware':
os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/hardware.py', 'report', *args])
if command in ['checkpoint', 'update', 'recover']:
diff --git a/os/tools/inspect_image.py b/os/tools/inspect_image.py
index 69659d7f2..035c6b599 100644
--- a/os/tools/inspect_image.py
+++ b/os/tools/inspect_image.py
@@ -32,6 +32,8 @@ def inspect(iso):
files = {str(p.relative_to(source / 'root')): p for p in (source / 'root').rglob('*') if p.is_file()}
files.update({'usr/lib/harness-os/install.py': source / 'installer.py',
'usr/lib/harness-os/onboarding.py': source / 'onboarding.py',
+ 'usr/lib/harness-os/network.py': source / 'network.py',
+ 'usr/lib/harness-os/projects.py': source / 'projects.py',
'usr/lib/harness-os/trial_projects.py': source / 'trial_projects.py',
'usr/lib/harness-os/system.py': source / 'system.py',
'usr/lib/harness-os/runtime_update.py': source / 'runtime_update.py',
diff --git a/os/tools/publish.py b/os/tools/publish.py
index 95747566e..20f4d19f7 100644
--- a/os/tools/publish.py
+++ b/os/tools/publish.py
@@ -177,14 +177,14 @@ def main():
for directory in ['machines', 'dsh-machines', 'hardware']:
for path in sorted((root / directory).rglob('*')):
include = path.suffix in {'.png', '.json', '.txt', '.jsonl'} or path.name.endswith('-boot-journal.log')
- if path.is_file() and include and 'Projects' not in path.relative_to(root / directory).parts:
+ if path.is_file() and include and not {'Projects', 'projects'} & set(path.relative_to(root / directory).parts):
archive.write(path, path.relative_to(root))
if examples:
with zipfile.ZipFile(folder / 'harness-examples.zip', 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for directory, kind in [('machines', 'workloads'), ('dsh-machines', 'dsh')]:
if kind not in examples:
continue
- for project_root in (root / directory).rglob('Projects'):
+ for project_root in (path for path in (root / directory).rglob('*') if path.name in {'Projects', 'projects'} and path.is_dir()):
for path in sorted(project_root.rglob('*')):
if path.is_file() and not set(path.relative_to(project_root).parts) & {'node_modules', '.git', '.harness', '__pycache__'}:
archive.write(path, path.relative_to(project_root))
@@ -203,7 +203,7 @@ def main():
Arch Linux with the LTS kernel, labwc, foot, and an on-demand browser. No desktop panels or preinstalled development stacks.
-To try it: follow the included `INSTALL.md` for Mac → USB → ThinkPad instructions. Verify the ISO's SHA-256, write the whole ISO to a USB stick, and boot an x86-64 PC with Secure Boot disabled. The USB asks for Wi-Fi when needed, then opens bundled OpenCode with its upstream model defaults and a local guide to Harness. Install without connecting works offline. Ask the agent to open installation, press Super+i, or click Install Harness in the persistent bottom dock. The same native form handles all three routes. Saved projects under ~/Projects are preserved during installation; temporary account credentials and running processes are not. Super+n opens New Harness, Super+m connects a computer, and Super+t opens a shell directly. All Super shortcuts require no Shift; existing Ctrl+b bindings remain available. This preview's installer erases the entire selected disk; it does not resize another OS. Encryption is enabled by default.
+To try it: follow the included `INSTALL.md` for Mac → USB → ThinkPad instructions. Verify the ISO's SHA-256, write the whole ISO to a USB stick, and boot an x86-64 PC with Secure Boot disabled. The USB asks for Wi-Fi when needed, then opens bundled OpenCode with its upstream model defaults and a local guide to Harness. Install without connecting works offline. Ask the agent to open installation, press Super+i, or click Install Harness in the persistent bottom dock. The same native form handles all three routes. Saved projects under ~/projects are preserved during installation; temporary account credentials and running processes are not. Super+n opens New Harness, Super+m connects a computer, and Super+t opens a shell directly. All Super shortcuts require no Shift; existing Ctrl+b bindings remain available. This preview's installer erases the entire selected disk; it does not resize another OS. Encryption is enabled by default.
{'The installer has four aligned fields: disk, encryption, password, repeat password. Disk choices fit on one line. Activate Install to begin; there is no second confirmation screen or minimum password length. Empty passwords are rejected. The account is me@harness. The password initially protects both the local account and, when enabled, the encrypted disk. There is no first-boot account wizard.' if interactive_install else ''}
diff --git a/os/tools/runtime-baseline.py b/os/tools/runtime-baseline.py
new file mode 100644
index 000000000..5d33bbbcd
--- /dev/null
+++ b/os/tools/runtime-baseline.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+"""Record published versions already contained in a source-built OS runtime."""
+import json
+from pathlib import Path
+import re
+import subprocess
+
+
+def baselines(source):
+ def git(*args):
+ return subprocess.check_output(['git', '-C', str(source), *args], text=True).strip()
+ if git('rev-parse', '--is-shallow-repository') != 'false':
+ raise ValueError('Runtime builds require full Git history and release tags (fetch-depth: 0).')
+ result = {}
+ for component, suffix in [('hn', 'tui'), ('cli', 'cli')]:
+ tags = git('tag', '--merged', 'HEAD', '--list', f'v*_{suffix}').splitlines()
+ candidates = []
+ for tag in tags:
+ match = re.fullmatch(r'v(\d{1,8}\.\d{1,8}\.\d{1,8})_' + suffix, tag)
+ if match:
+ candidates.append((tuple(map(int, match[1].split('.'))), tag, match[1]))
+ if candidates:
+ _, tag, version = max(candidates)
+ result[component] = {'version': version, 'commit': git('rev-parse', tag + '^{commit}')}
+ return result
+
+
+if __name__ == '__main__':
+ print(json.dumps(baselines(Path(__file__).resolve().parents[2])))
diff --git a/tui/src/app.rs b/tui/src/app.rs
index db185fe99..5feaf6712 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -665,6 +665,7 @@ pub struct App {
/// A disposable USB session offers direct try, install and network actions on its home.
pub os_live: bool,
pub os_welcome: crate::os_welcome::State,
+ pub os_first_use: bool,
/// While a command runs in another session (`-t work:2`): the session to come back to.
pub swap_back: Option<u32>,
/// The session asked for at start (`hn new -A -s main`, `hn attach -t work`).
@@ -873,6 +874,7 @@ impl App {
os_session: std::env::var("HARNESS_OS").as_deref() == Ok("1"),
os_live: std::env::var("HARNESS_OS").as_deref() == Ok("1") && std::env::var("HARNESS_OS_LIVE").as_deref() == Ok("1"),
os_welcome: Default::default(),
+ os_first_use: std::env::var("HARNESS_OS_FIRST_USE").as_deref() == Ok("1"),
wait_channels: HashMap::new(),
cli_held: std::collections::VecDeque::new(),
last_cli: Instant::now(),
@@ -1994,7 +1996,7 @@ impl App {
let front = self.swap_back.is_none_or(|b| b == self.session_id) && self.tabs.get(self.active).map(|t| t.id == tab.id).unwrap_or(false);
let manual = self.options.get("window-size", &tab.id, None).as_deref() == Some("manual");
let creating = self.shell_inputs.contains_key(&tab.id) && tab.size.is_some();
- if !self.headless && self.swap_back.is_none_or(|b| b == self.session_id) && !manual && !creating && (front || tab.root.is_none()) { return crate::os_welcome::workspace(self, tab, self.body()) }
+ if !self.headless && self.swap_back.is_none_or(|b| b == self.session_id) && !manual && !creating && (front || tab.root.is_none()) { return self.body() }
let (w, h) = tab.root.as_ref().map(|r| r.size()).unwrap_or_else(|| tab.size.unwrap_or(self.default_size()));
Rect::new(0, if front && !self.headless { self.body().y } else { 0 }, w, h)
}
@@ -3663,7 +3665,7 @@ impl App {
}
// The bar down a side takes its columns.
if let Some(bar) = self.bar_rect() { return Rect::new(if bar.x == 0 { bar.width } else { 0 }, 0, self.size.0.saturating_sub(bar.width), self.size.1) }
- Rect::new(0, if self.status_top { n } else { 0 }, self.size.0, self.size.1.saturating_sub(n + crate::os_welcome::dock_height(self)))
+ Rect::new(0, if self.status_top { n } else { 0 }, self.size.0, self.size.1.saturating_sub(n))
}
/// tmux's status option: how many status lines (off, on, 2 … 5).
@@ -5272,7 +5274,7 @@ impl App {
// The OS opens on the agent launcher. An explicit `hn new ...` still gets
// its requested shell; reconnecting to existing work is handled by the desk.
if self.os_session && self.start_session.is_none() {
- if self.os_live && self.tabs.len() == 1 && self.tabs[0].root.is_none() {
+ if (self.os_live || self.os_first_use) && self.tabs.len() == 1 && self.tabs[0].root.is_none() {
if self.link(&self.fleet.local_id).is_none() { return }
self.shell_asked = true;
// The welcome reply may arrive after another terminal is requested.
diff --git a/tui/src/mouse.rs b/tui/src/mouse.rs
index 364c261ac..1fde805d6 100644
--- a/tui/src/mouse.rs
+++ b/tui/src/mouse.rs
@@ -230,7 +230,7 @@ fn check(app: &mut App, m: &mut Event, double: bool) -> Option<Key> {
m.ignore = ignore;
let lines = app.status_lines();
m.statuslines = lines;
- m.statusat = if lines == 0 { -1 } else if app.status_top { 0 } else { app.size.1.saturating_sub(lines + crate::os_welcome::dock_height(app)) as i32 };
+ m.statusat = if lines == 0 { -1 } else if app.status_top { 0 } else { app.size.1.saturating_sub(lines) as i32 };
(m.ox, m.oy) = app.bar_offset();
let mut place = None;
if m.statusat != -1 && (y as i32) >= m.statusat && (y as i32) < m.statusat + lines as i32 {
diff --git a/tui/src/os_welcome.rs b/tui/src/os_welcome.rs
index 00a1b928e..577046641 100644
--- a/tui/src/os_welcome.rs
+++ b/tui/src/os_welcome.rs
@@ -1,7 +1,7 @@
-//! USB onboarding belongs to the OS launcher. Ordinary hn never enters this module's UI.
+//! OS first-use startup and the USB install action. Ordinary hn never enters this UI.
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
-use ratatui::{buffer::Buffer, layout::Rect, text::Line};
-use crate::{app::{App, Placement, Tab}, theme::{self, bold, fg}};
+use ratatui::{buffer::Buffer, layout::Rect, style::{Modifier, Style}};
+use crate::{app::{App, At, Placement}, layout::Dir};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action { Install, Wifi, New, Connect, Terminal, Dismiss }
@@ -11,7 +11,7 @@ pub struct State {
pub guide_pane: Option<u64>,
pub dock_focus: Option<Action>,
pub hits: Vec<(Rect, Action)>,
- pub network: Option<bool>,
+ starter_tab: Option<String>,
welcome_panes: Vec<u64>,
install_pane: Option<u64>,
wifi_pane: Option<u64>,
@@ -21,24 +21,18 @@ pub struct State {
pub fn live(app: &App) -> bool { app.os_session && app.os_live && !app.headless }
-pub fn dock_height(app: &App) -> u16 { u16::from(live(app) && app.size.1 > 2) }
-
pub fn tick(app: &mut App) {
- if !live(app) || app.tick % 8 != 0 { return }
+ if !app.os_session || app.tick % 8 != 0 { return }
app.os_welcome.welcome_panes.retain(|id| app.panes.contains_key(id));
- app.os_welcome.network = std::fs::read_to_string("/run/harness-network").ok().and_then(|text| match text.trim() {
- "connected" => Some(true), "offline" => Some(false), _ => None,
- });
-}
-
-pub fn intro(app: &App, tab: &Tab) -> bool {
- live(app) && app.size.0 >= 80 && app.size.1 >= 18 && !tab.zoomed
- && app.os_welcome.guide_pane.is_some_and(|id| tab.panes() == [id])
}
-pub fn workspace(app: &App, tab: &Tab, mut area: Rect) -> Rect {
- if intro(app, tab) { area.width /= 2; }
- area
+fn split_starter(app: &mut App, pane: u64, dir: Dir, command: &str) {
+ let Some(tab) = app.tabs.iter().find(|tab| tab.panes().contains(&pane)) else { return };
+ let placement = Placement::At(At { tab: tab.id.clone(), pane: Some(pane), dir,
+ before: false, full: false, size: Some((50, true)), detached: true, zoom: false });
+ // Target the original pane explicitly. A delayed create reply must not split
+ // a different tab or steal focus from work opened while networking finished.
+ crate::input::new_shell_from(app, None, placement, None, Some(command.into()));
}
fn this_computer(app: &App, machine: &str) -> bool {
@@ -51,10 +45,16 @@ pub fn shell_created(app: &mut App, id: u64) {
if !app.os_session { return }
let Some(pane) = app.panes.get(&id) else { return };
if !this_computer(app, &pane.machine_id) { return }
- match pane.start_command.as_deref() {
- Some("/usr/bin/hn-os welcome") if live(app) => {
+ let command = pane.start_command.clone();
+ match command.as_deref() {
+ Some("/usr/bin/hn-os welcome") => {
if !app.os_welcome.welcome_panes.contains(&id) { app.os_welcome.welcome_panes.push(id); }
}
+ Some("/usr/bin/hn-os starter upper") if app.os_welcome.starter_tab.as_ref().is_some_and(|tab|
+ app.tabs.iter().any(|t| &t.id == tab && t.panes().contains(&id))) => {
+ app.os_welcome.starter_tab = None;
+ split_starter(app, id, Dir::Vertical, "/usr/bin/hn-os starter lower");
+ }
Some("sudo /usr/bin/harness install") if live(app) => app.os_welcome.install_pane = Some(id),
Some("/usr/bin/hn-os wifi") => app.os_welcome.wifi_pane = Some(id),
_ => {}
@@ -101,18 +101,23 @@ pub fn command(app: &mut App, args: &[String]) {
if !app.os_session || app.headless { return app.error("This action belongs to the Harness operating system.") }
if app.read_only() { return app.error("This client is read-only.") }
if args.first().map(String::as_str) == Some("ready") {
- if !live(app) { return app.error("The USB welcome is not active.") }
let Some(hint) = args.get(1).filter(|id| id.strip_prefix('%').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))) else {
- return app.error("The USB welcome must identify its pane.");
+ return app.error("The welcome must identify its pane.");
};
// A tmux-backed shell sees the backend's %N, not hn's independent pane
// number. Native fallback shells deliberately export hn's own number.
let pane = app.os_welcome.welcome_panes.iter().copied().find(|id| app.panes.get(id).is_some_and(|p|
this_computer(app, &p.machine_id) && if crate::local::is_local(&p.machine_id) { crate::pane::tag(*id) == *hint }
else { app.fleet.agent(&p.machine_id, &p.agent_id).is_some_and(|a| a.tmux_pane == *hint) }));
- let Some(pane) = pane else { return app.error("That pane is not the USB welcome on this computer.") };
+ let Some(pane) = pane else { return app.error("That pane is not the welcome on this computer.") };
+ if app.os_welcome.guide_pane == Some(pane) { return }
app.os_welcome.guide_pane = Some(pane);
- app.fit_panes();
+ if app.size.0 >= 80 && app.size.1 >= 18 {
+ if let Some(tab) = app.tabs.iter().find(|tab| tab.panes() == [pane]) {
+ app.os_welcome.starter_tab = Some(tab.id.clone());
+ split_starter(app, pane, Dir::Horizontal, "/usr/bin/hn-os starter upper");
+ }
+ }
return;
}
let action = match args.first().map(String::as_str) {
@@ -124,71 +129,32 @@ pub fn command(app: &mut App, args: &[String]) {
act(app, action);
}
-fn button(buf: &mut Buffer, app: &mut App, area: Rect, text: &str, action: Action, primary: bool) {
- if area.width == 0 || area.height == 0 { return }
- let style = if primary || app.os_welcome.dock_focus == Some(action) { bold(theme::accent()) }
- else if action == Action::Wifi && app.os_welcome.network == Some(false) { fg(theme::WARN) }
- else { fg(theme::MUTED) };
- let style = if app.os_welcome.dock_focus == Some(action) { style.add_modifier(ratatui::style::Modifier::REVERSED) } else { style };
- buf.set_line(area.x, area.y, &Line::styled(text, style), area.width);
- app.os_welcome.hits.push((area, action));
-}
-
-pub fn draw_intro(buf: &mut Buffer, app: &mut App) {
- app.os_welcome.hits.clear();
- if !intro(app, app.tab()) || app.modal.is_some() { return }
- let body = app.body();
- let left = body.x + body.width / 2 + 1;
- let width = body.right().saturating_sub(left + 2);
- let half = body.height / 2;
- for y in body.y..body.bottom() { buf.set_string(left - 1, y, "│", fg(theme::MUTED)); }
- for x in left..body.right() { buf.set_string(x, body.y + half, "─", fg(theme::MUTED)); }
- button(buf, app, Rect::new(body.right() - 5, body.y, 5, 1), "[ x ]", Action::Dismiss, false);
- for (row, title, lines, action, label) in [
- (body.y, "More agents. More possibilities.", ["Give each agent its own work.", "Choose an agent and a project.", "Super+n"], Action::New, "[ New Harness ]"),
- (body.y + half, "Your computers, together.", ["Run agents on another computer.", "Keep their work here beside you.", "Super+m"], Action::Connect, "[ Connect a computer ]"),
- ] {
- let mut y = row + 1;
- for (text, style) in std::iter::once((title, bold(theme::TEXT)))
- .chain(std::iter::once(("", fg(theme::TEXT))))
- .chain(lines.into_iter().map(|line| (line, fg(theme::MUTED)))) {
- if y >= row + half || y >= body.bottom() { break }
- buf.set_line(left + 1, y, &Line::styled(text, style), width);
- y += 1;
- }
- if y < body.bottom() { button(buf, app, Rect::new(left + 1, y, width.min(label.len() as u16), 1), label, action, true); }
- }
-}
-
+/// The install action uses the existing status line's named range. The normal
+/// window list keeps its own space, selection and mouse handling on the left.
pub fn draw_dock(buf: &mut Buffer, app: &mut App) {
- if dock_height(app) == 0 { return }
- let (width, y) = (app.size.0, app.size.1 - 1);
- let area = Rect::new(0, y, width, 1);
- buf.set_style(area, fg(theme::TEXT));
- for x in 0..width { if let Some(cell) = buf.cell_mut((x, y)) { cell.set_symbol(" "); } }
- let invitation = if width >= 76 { "Make Harness your OS. " } else { "" };
- if !invitation.is_empty() { buf.set_line(1, y, &Line::raw(invitation), width.saturating_sub(1)); }
- let x = 1 + invitation.len() as u16;
- let install = "[ Install Harness ]";
- button(buf, app, Rect::new(x, y, width.saturating_sub(x).min(install.len() as u16), 1), install, Action::Install, true);
- let secondary = if width >= 56 { "Temporary USB " } else { "USB " };
- let wifi = if app.os_welcome.network == Some(false) { "[ Wi-Fi: offline ]" } else { "[ Wi-Fi ]" };
- let wifi_width = wifi.len() as u16;
- let tail = secondary.len() as u16 + wifi_width + 1;
- if width >= x + install.len() as u16 + tail + 2 {
- let start = width - tail;
- buf.set_line(start, y, &Line::styled(secondary, fg(theme::MUTED)), secondary.len() as u16);
- button(buf, app, Rect::new(width - wifi_width - 1, y, wifi_width, 1), wifi, Action::Wifi, false);
+ app.os_welcome.hits.clear();
+ if !live(app) || app.modal.is_some() || app.status_lines() == 0 { return }
+ let y = if app.status_top { 0 } else { app.size.1.saturating_sub(app.status_lines()) };
+ let ranges: Vec<_> = app.status_ranges.iter().filter(|(row, range)| *row == 0 &&
+ matches!(&range.kind, crate::draw::RangeKind::User(name) if name == "os-install")).map(|(_, range)| (range.start, range.end)).collect();
+ for (start, end) in ranges {
+ let area = Rect::new(start, y, end.min(app.size.0).saturating_sub(start), 1);
+ if area.width == 0 { continue }
+ // Keep the status line's foreground/background contrast. The terminal
+ // accent can be nearly invisible on a light status background.
+ let style = Style::default().add_modifier(Modifier::BOLD);
+ let style = if app.os_welcome.dock_focus.is_some() { style.add_modifier(Modifier::REVERSED) }
+ else { style };
+ buf.set_style(area, style);
+ app.os_welcome.hits.push((area, Action::Install));
}
}
pub fn mouse(app: &mut App, event: MouseEvent) -> bool {
if !live(app) || app.modal.is_some() { return false }
- let in_dock = dock_height(app) > 0 && event.row == app.size.1 - 1;
- if !matches!(event.kind, MouseEventKind::Down(MouseButton::Left)) { return in_dock }
- let action = app.os_welcome.hits.iter().find(|(rect, _)| rect.contains((event.column, event.row).into())).map(|(_, action)| *action);
- if let Some(action) = action { act(app, action); return true }
- in_dock
+ let hit = app.os_welcome.hits.iter().any(|(rect, _)| rect.contains((event.column, event.row).into()));
+ if hit && matches!(event.kind, MouseEventKind::Down(MouseButton::Left)) { act(app, Action::Install); }
+ hit
}
pub fn key(app: &mut App, key: KeyEvent) -> bool {
@@ -200,7 +166,7 @@ pub fn key(app: &mut App, key: KeyEvent) -> bool {
if let Some(action) = app.os_welcome.dock_focus {
match key.code {
KeyCode::Esc => app.os_welcome.dock_focus = None,
- KeyCode::Tab | KeyCode::BackTab | KeyCode::Left | KeyCode::Right => app.os_welcome.dock_focus = Some(if action == Action::Install { Action::Wifi } else { Action::Install }),
+ KeyCode::Tab | KeyCode::BackTab | KeyCode::Left | KeyCode::Right => {}
KeyCode::Enter | KeyCode::Char(' ') => act(app, action),
_ => { app.os_welcome.dock_focus = None; return false }
}
@@ -227,59 +193,36 @@ mod tests {
(0..buf.area.height).map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n")
}
- #[tokio::test]
- async fn dock_is_usb_only_and_keeps_its_controls_inside_small_screens() {
- for (width, height) in [(20, 8), (60, 18), (80, 24), (120, 40)] {
- let mut app = fixture(width, height);
- for (os, usb) in [(false, false), (false, true), (true, false), (true, true)] {
- app.os_session = os;
- app.os_live = usb;
- let mut buffer = Buffer::empty(Rect::new(0, 0, width, height));
- draw_intro(&mut buffer, &mut app);
- draw_dock(&mut buffer, &mut app);
- let text = contents(&buffer);
- assert_eq!(text.contains("Install Harness"), os && usb, "{text}");
- if os && usb && width >= 80 {
- assert!(text.contains("Make Harness your OS."), "{text}");
- assert!(text.contains("Temporary USB"), "{text}");
- assert!(text.contains("[ Wi-Fi ]"), "{text}");
- }
- assert!(app.os_welcome.hits.iter().all(|(rect, _)| rect.right() <= width && rect.bottom() <= height));
- }
- }
+ fn render(app: &mut App) -> Buffer {
+ use ratatui::{Terminal, backend::TestBackend};
+ app.options.global_session.insert("status-right".into(), "Make Harness your OS. #[range=user|os-install bold][ Install Harness ]#[norange]".into());
+ let mut terminal = Terminal::new(TestBackend::new(app.size.0, app.size.1)).unwrap();
+ terminal.draw(|frame| crate::ui::draw(frame, app)).unwrap();
+ terminal.backend().buffer().clone()
}
#[tokio::test]
- async fn introduction_uses_half_the_screen_only_for_its_one_agent() {
- let mut app = fixture(120, 40);
- app.tab_mut().root = Some(crate::layout::Node::new(1, 120, 38));
- app.os_welcome.guide_pane = Some(1);
- assert_eq!(app.window_area(app.tab()).width, 60);
- assert_eq!(app.body().height, 38, "status and install dock each reserve one row");
- let mut buffer = Buffer::empty(Rect::new(0, 0, 120, 40));
- draw_intro(&mut buffer, &mut app);
- let text = contents(&buffer);
- assert!(text.contains("[ New Harness ]") && text.contains("[ Connect a computer ]"), "{text}");
- app.tab_mut().zoomed = true;
- assert_eq!(app.window_area(app.tab()).width, 120);
- app.tab_mut().zoomed = false;
- app.os_welcome.guide_pane = Some(2);
- assert_eq!(app.window_area(app.tab()).width, 120, "unrelated panes keep their full space");
- app.os_live = false;
- assert_eq!(app.body().height, 39, "installed Harness has no USB dock");
+ async fn footer_shares_one_row_with_windows_and_leaves_pane_space_intact() {
+ for (width, height) in [(40, 8), (80, 24), (120, 40)] {
+ let mut app = fixture(width, height);
+ let buffer = render(&mut app);
+ let text = contents(&buffer);
+ assert!(text.contains("Install Harness"), "{text}");
+ assert!(!text.contains("Temporary USB") && !text.contains("Wi-Fi: offline"));
+ assert_eq!(app.body().height, height - 1);
+ assert!(app.os_welcome.hits.iter().all(|(rect, _)| rect.right() <= width && rect.y == height - 1));
+ assert!(!app.os_welcome.hits.is_empty(), "install range was lost: {text}");
+ }
}
#[tokio::test]
- async fn keyboard_dock_does_not_steal_the_agents_tab_or_ordinary_hn_f10() {
+ async fn keyboard_footer_does_not_steal_the_agents_tab_or_ordinary_hn_f10() {
let mut app = fixture(100, 30);
let press = |code| KeyEvent::new(code, KeyModifiers::NONE);
assert!(!key(&mut app, press(KeyCode::Tab)));
assert!(key(&mut app, press(KeyCode::F(10))));
assert_eq!(app.os_welcome.dock_focus, Some(Action::Install));
- assert!(key(&mut app, press(KeyCode::Tab)));
- assert_eq!(app.os_welcome.dock_focus, Some(Action::Wifi));
assert!(key(&mut app, press(KeyCode::Esc)));
- assert!(app.os_welcome.dock_focus.is_none());
app.os_session = false;
assert!(!key(&mut app, press(KeyCode::F(10))));
}
@@ -320,21 +263,19 @@ mod tests {
}
#[tokio::test]
- async fn mouse_dock_does_not_click_through_modals_or_fall_into_the_status_bar() {
- let mut app = fixture(100, 30);
- let mut buffer = Buffer::empty(Rect::new(0, 0, 100, 30));
- draw_dock(&mut buffer, &mut app);
+ async fn install_click_does_not_steal_window_clicks_or_cross_a_modal() {
+ let mut app = fixture(120, 30);
+ render(&mut app);
let click = |x| MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: x, row: 29, modifiers: KeyModifiers::NONE };
- assert!(mouse(&mut app, click(0)), "empty dock cells belong to the dock");
+ assert!(!mouse(&mut app, click(0)), "window list still receives its clicks");
+ let install = app.os_welcome.hits[0].0;
app.modal = Some(crate::modal::Modal::Confirm { prompt: "existing form".into(), command: "".into(), key: 'y', enter_yes: false });
- let install = app.os_welcome.hits.iter().find(|(_, a)| *a == Action::Install).unwrap().0;
assert!(!mouse(&mut app, click(install.x)));
- assert!(matches!(app.modal, Some(crate::modal::Modal::Confirm { .. })));
app.modal = None;
- app.os_welcome.network = Some(false);
- draw_intro(&mut buffer, &mut app);
- draw_dock(&mut buffer, &mut app);
- assert!(contents(&buffer).contains("Wi-Fi: offline"));
+ app.os_live = false;
+ assert!(!mouse(&mut app, click(install.x)));
+ app.os_live = true;
+ assert!(mouse(&mut app, click(install.x)));
}
#[tokio::test]
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index 6a517cdc4..f31033a94 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -171,7 +171,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) {
}
// The status lines (tmux's status: off, on, 2 … 5), at the bottom or (status-position) the top.
let lines = app.status_lines().max(1).min(area.height);
- let status = Rect::new(0, if app.status_top { 0 } else { area.height.saturating_sub(lines + crate::os_welcome::dock_height(app)) }, area.width, lines);
+ let status = Rect::new(0, if app.status_top { 0 } else { area.height.saturating_sub(lines) }, area.width, lines);
let body = app.body();
// The window in front at the terminal's size, whatever brought it there.
let window_area = app.window_area(app.tab());
@@ -193,7 +193,6 @@ pub fn draw(frame: &mut Frame, app: &mut App) {
// ── status bar ──
// The status bar down a side, and the tabs over the panes beside it.
crate::bar::draw(buf, app);
- crate::os_welcome::draw_intro(buf, app);
if let Some(Modal::DisplayPanes { .. }) = &app.modal { display_panes(buf, app) }
let search_busy = app.said_due.is_some() || app.said_pending > 0;
let msg_style = app.message_style();