The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Start Harness USB trials with an agent and direct installation (#703)
Dee7824fc63698e
diff --git a/docs/naming-system.md b/docs/naming-system.mdindex 8efb3d8b6..cbf4d409c 100644--- a/docs/naming-system.md+++ b/docs/naming-system.md@@ -89,7 +89,7 @@ task form.| Manage a workspace group | **Rename Tab**, **Close Tab**, **Next Tab**, **Previous Tab** || Manage a running harness | **Rename Harness**, **Pause Harness**, **Resume Harness**, **Restart Harness**, **Stop Harness** || Author a reusable Store package | **Create Harness** |-| Start the bundled agent from the OS welcome | **Start OpenCode** |+| Start the bundled agent from the installed OS home | **Start OpenCode** || Set up wireless networking | **Connect to Wi-Fi** |Use the object's own name where possible: **Blender**, **Web Viewer**, or the@@ -102,8 +102,11 @@ configuration where it affects a decision.| --- | --- || Boot and unlock branding | **Harness** || Disk unlock prompt | **Enter your password** |-| USB welcome primary action | **Install Harness** |-| USB welcome secondary action | **Try without installing** |+| USB install action | **Install Harness** |+| Offline USB action | **Install without connecting** |+| USB dock invitation | **Make Harness your OS.** |+| USB dock session label | **Temporary USB** |+| Connect another execution machine | **Connect a computer** || Installer title | **Install Harness** || Installer fields | **Disk**, **Encryption**, **Password**, **Repeat password** || Installer action | **Install** |@@ -112,15 +115,23 @@ configuration where it affects a decision.| Default account | `me` || Default computer name | `harness` || Default shell identity | `me@harness` |-| Command equivalent of installation | `sudo harness install` |-| OS page description | **An operating system built around agents.** |+| Open installation from a conversation or shell | `harness install` |+| Direct administrative installation command | `sudo harness install` |+| OS page description | **A Linux operating system built by agents, for agents.** || Audience description | **Built for programmers first.** |-Installation is directly accessible from the USB welcome. Trying Harness may-require network setup; offline installation does not. An installed system and+The USB opens network setup when disconnected, with **Install without connecting**+always available. Once connected, it opens the bundled agent and keeps the+installation dock visible. An installed system andordinary hn on macOS or another Linux distribution never show the USB installationactions. The `harness install` system command belongs to the OS integration.+Write OS shortcuts with lowercase letters: **Super+n**, **Super+t**, **Super+m**,+**Super+i**, **Super+w**, **Super+b**, **Super+u**, **Super+l**. They require no Shift+and no prefix. The existing shared TUI prefix shortcuts remain available; write+**Ctrl+b, then Shift+n** when that binding requires Shift. Super means the Windows+key on PC keyboards and the Command key on Mac keyboards running Harness OS.+The terminal and optional browser are the OS's working surfaces. This does notreplace the desktop app's design system or require every Harness interface toadopt the OS welcome screen.diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex f0714af88..18036af81 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -165,8 +165,8 @@ OS windows use hn's local session storage (`HARNESS_TUI_DESK=off`), so theirlayout and pane references survive reconnects without signing into the cloud.This setting is confined to the OS launcher; ordinary hn installs are unchanged.-`Update ready · Super+U` appears in the bottom bar. Super+U opens the keyboard-update action (Ctrl+B, Shift+U remains an alias). Enter applies the prepared+`Update ready · Super+u` appears in the bottom bar. Super+u opens the keyboard+update action (Ctrl+b, Shift+u remains an alias). Enter applies the preparedruntime through a transient user service. An hn-only change reconnects just thescreen; a CLI change also restarts its supervised service. Failure restores theprevious selection. Restore previous version holds the rejected versions until@@ -183,7 +183,7 @@ ISO is not a requirement for a TUI update. The public previewvalidated preview 5 release; it does not need to be flashed again.`development_update=true` builds a private, deliberately unpublished `999.0.1`-hn/CLI fixture. The installed VM's actual timer stages it, then real Super+U and+hn/CLI fixture. The installed VM's actual timer stages it, then real Super+u andEnter keys apply hn and CLI independently. Acceptance checks the same terminalprocess, a live OpenCode process, keyboard input, rollback and an unchanged bootID. Those fixture binaries are never included in the package or public channel.@@ -270,6 +270,44 @@ change, explicitly approved for all platforms. Publishing the ISO did not releasthese through the general TUI channel. The small updater adds no changes to `tui/`or `cli/`.+## Agent-led USB onboarding++The live launcher starts `hn-os welcome` in one real terminal pane. While offline,+a small curses step offers Wi-Fi or the native installer without needing a model.+Once connected, it execs packaged OpenCode immediately. The OS-only TUI integration+adds two starter panels and a one-row install dock. `hn os-action` is a private+integration command, guarded by OS mode; install additionally requires live mode.+All install entry points create or focus one local form even if a remote pane has+focus. Super bindings live in labwc; the shared Ctrl+b key tables are preserved.++OpenCode reads the packaged guide through its global+`~/.config/opencode/AGENTS.md`, linked to `/usr/share/harness-os/guide.md`.+The account skeleton supplies this link; Start OpenCode also adds it on older+installations when no personal instructions file exists. Existing instructions+are never replaced. OpenCode 2 accepts the legacy JSON `instructions` field but+does not load it; see its [instructions reference](https://opencode.ai/v2/docs/instructions/).+The guide+points to the exact shipped `tui/README.md`, with a source revision, and tells the+agent to inspect current bindings before answering. Model/provider selection is+left to upstream. The package-owned OpenCode executable is updated by full system+updates; new accounts disable its self-updater through the global config.+Existing user preferences are preserved. No download blocks the first conversation.+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+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+saved-file transfer, not a migration of processes or the live home/credentials.++Validation must cover offline entry/cancellation, Ethernet skip, the real default+agent answering TUI questions and creating a project, agent-requested installation,+keyboard and mouse controls, plain/encrypted offline installation, post-boot file+hashes, and ordinary Mac/Linux TUI isolation. Native VM screenshots are required+before publication; local unit tests alone do not establish this experience.+## Optional remote VM controls`run-vm.py --vnc-port 5901 --ssh-port 2222 --remote-host me@build-hostdiff --git a/os/INSTALL.md b/os/INSTALL.mdindex 59f5656e1..85be9a733 100644--- a/os/INSTALL.md+++ b/os/INSTALL.md@@ -1,6 +1,6 @@# Install Harness on a ThinkPad-These instructions are for **0.1.0-preview.6**, using a Mac to prepare the USB.+These instructions are for **0.1.0-preview.7**, using a Mac to prepare the USB.The USB starts a live session. Installation begins only when you choose **Install**in the installer; it erases the entire selected disk.@@ -21,20 +21,20 @@ compute still need testing on the actual hardware.## 2. Download and verify on the Mac-From the [preview 6 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.6),+From the [preview 7 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.7),download both files into the same folder:-- `harness-0.1.0-preview.6-x86_64.iso`-- `harness-0.1.0-preview.6-x86_64.iso.sha256`+- `harness-0.1.0-preview.7-x86_64.iso`+- `harness-0.1.0-preview.7-x86_64.iso.sha256`If they are in Downloads, open Terminal and run:```shcd ~/Downloads-shasum -a 256 -c harness-0.1.0-preview.6-x86_64.iso.sha256+shasum -a 256 -c harness-0.1.0-preview.7-x86_64.iso.sha256```-The result must say `harness-0.1.0-preview.6-x86_64.iso: OK`.+The result must say `harness-0.1.0-preview.7-x86_64.iso: OK`.If it does not, download the files again before flashing.## 3. Flash the USB@@ -64,9 +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 welcome screen offers **Enter — Install Harness** and **T — Try without-installing**. No account or password is needed to use the live session. Work in-the USB session is temporary and is not copied during installation.+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+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.++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+installing, or copy important work to another drive.### Trying an older Intel Mac@@ -79,7 +90,7 @@ Try explains that limitation before attempting to start it.Shut down, insert the USB, then hold **Option (⌥)** while turning on the Mac.Choose the external **EFI Boot** entry. Apple's[startup-key guide](https://support.apple.com/en-us/102603) describes that menu.-Start with **T — Try without installing** and check built-in keyboard, trackpad,+Connect and try the agent first; check built-in keyboard, trackpad,Wi-Fi, brightness and sound before choosing the internal disk. Installation usesthe same form below and erases the whole selected disk, including macOS.@@ -89,8 +100,10 @@ IDs and driver names, without serial numbers or Wi-Fi passwords.## 5. Install-Press **Enter** on the welcome screen. You do not need to open a terminal or type-a command. The form has four fields:+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+the same native form, with four fields:1. **Disk:** press Enter, choose the internal disk by its model and capacity, andpress Enter again. The live USB is excluded from the choices.@@ -110,8 +123,9 @@ The account and computer name are set to **`me@harness`**. Installation works ofWhen **Harness is installed.** appears, choose **Shut down**. Once the ThinkPad isoff, remove the USB and power it on.-While trying the live system, **Ctrl+B**, then **I** opens the same installer.-The equivalent terminal command is `sudo harness install`.+The existing **Ctrl+b, then Shift+i** shortcut also opens the installer.+`harness install` opens the form from a conversation or terminal; disk selection+and passwords stay in the form. `sudo harness install` runs it directly.## 6. First boot@@ -126,7 +140,7 @@ There is no cloud account that resets the disk password.On the empty home screen, press **Enter** to start OpenCode. If there is no networkconnection, the keyboard network picker opens first. Select your Wi-Fi network-and enter its password there. **Ctrl+B**, then **W** opens network setup from any+and enter its password there. **Super+w** opens network setup from anypane. Ethernet connects automatically when available.OpenCode is already installed and uses its upstream defaults. Available models@@ -135,19 +149,22 @@ model setup. A Linux account does not sign you into an agent provider.## 7. Use it-**Super** means the Windows-logo key on a typical ThinkPad. For a Ctrl+B shortcut,-press Ctrl+B, release both keys, then press the indicated letter. Capital letters-below mean **Shift + letter**.+**Super** means the Windows-logo key on a PC keyboard, or Command on a Mac keyboard+running Harness OS. These shortcuts require no Shift and no Ctrl+b prefix. The+shared TUI's Ctrl+b shortcuts remain available; release the prefix before pressing+the next key. A capital letter in a prefix binding means Shift + letter.| Keys or command | Action || --- | --- |-| Ctrl+B, then N | New Harness: choose an agent |-| Ctrl+B, then T | New terminal: open a shell directly |-| Ctrl+B, then W | Connect to Wi-Fi |-| Super+B | Open/focus Chromium, or return to Harness |+| Super+n | New Harness: choose an agent |+| Super+t | New terminal: open a shell directly |+| Super+m | Connect a computer |+| Super+w | Connect to Wi-Fi |+| Super+i | Install Harness (USB only) |+| Super+b | Open/focus Chromium, or return to Harness || Super+Enter | Focus Harness |-| Super+L | Lock; unlock with the account password |-| Super+U | Updates |+| Super+l | Lock; unlock with the account password |+| Super+u | Updates || `hn-browser http://localhost:3000` | Open a local project in the browser || `sudo systemctl poweroff` | Shut down |@@ -156,8 +173,8 @@ 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.+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.@@ -174,7 +191,7 @@ sha256sum -c SHA256SUMSsudo python3 apply-update.py apply "$PWD"```-Reboot when it finishes; subsequent updates are available through Super+U.+Reboot when it finishes; subsequent updates are available through Super+u.If the bootstrap fails, use `sudo python3 apply-update.py rollback` from thatsame folder before trying again.diff --git a/os/README.md b/os/README.mdindex d0fb4dbb4..91a5fc926 100644--- a/os/README.md+++ b/os/README.md@@ -1,6 +1,6 @@# Harness-An operating system built around agents. Boot into `hn`, describe the work,+A Linux operating system built by agents, for agents. Boot into `hn`, describe the work,and let an agent use the tools it needs. Review its diffs, tests and output inthe terminal; open the browser when the work needs a visual surface.@@ -11,12 +11,20 @@ audience, not its name.Product names and interface copy follow the [Naming System](../docs/naming-system.md).+**Preview 7 candidate (not yet published):** 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+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.+**Preview 6:** the USB welcome offers **Install Harness** or **Try without installing**.Install works offline. Try opens Wi-Fi setup when needed, then bundled OpenCodewith its upstream default settings. The installer has four fields and one Installaction; 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;+`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.[Download preview 6](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.6)@@ -49,10 +57,10 @@ installation does not need reinstalling solely for the USB payload-location fix.foot or add a second graphical Harness client.If graphics initialization fails, the login session falls back to hn on theLinux console so drivers can be repaired without a working compositor.-- Chromium is installed but does not start at boot. `Super+B` opens/focuses it or+- Chromium is installed but does not start at boot. `Super+b` opens/focuses it orreturns to hn. `Super+Enter` focuses hn; `Alt+Tab` switches available windows.Browser sandboxing and hardware acceleration remain enabled.-- `Ctrl+B`, then `N` opens the agent picker; `Ctrl+B`, then `T` opens a terminal directly. The normal session+- `Ctrl+b`, then `Shift+n` opens the agent picker; `Ctrl+b`, then `Shift+t` opens a terminal directly. The normal sessionhas no interactive parent shell to exit into. Shells remain available in hn panes. This isan interface policy, not confinement against someone with shell/admin access.- NetworkManager, fonts, clipboard, audio, locking, firmware and zram provide@@ -120,10 +128,20 @@ machine can reach Harness but is not supported for the bundled agent trial.The [installation guide](INSTALL.md) covers theMac download, checksum, flashing and ThinkPad boot menu in full.-On the USB welcome, press **Enter** to install or **T** to try Harness. Installation-needs no network or terminal command. Trying a cloud agent requires a connection;-network setup opens when needed. Work in the live USB session is temporary and is-not copied during installation.+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+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+installed home and verified by hash. Work elsewhere remains temporary. Running+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.The installer uses `me@harness`. Choose **Disk**, leave **Encryption** enabled orchange it, then enter **Password** and **Repeat password**. **Install immediately@@ -138,21 +156,24 @@ shows the Harness logo and **Enter your password**, then enters hn. An unencryptinstall requires login as `me`. The password initially protects both the accountand, when enabled, the disk. There is no first-boot account wizard.-The command equivalent is `sudo harness install`. Advanced overrides remain:+`harness install` opens the same form from an agent or terminal on the USB;+`sudo harness install` runs it directly. Advanced overrides remain:`--no-encryption`, `--username NAME`, and `--hostname NAME`. With an unattended`--config` file, set `username`, `hostname` and `encrypt` in that file instead.Ordinary hn on macOS or another Linux distribution does not expose OS installation.-On the installed system's empty home, Enter starts OpenCode. `Ctrl+B`, then `W`-opens network setup; `Ctrl+B`, then `T` opens a shell directly. Capital letters-in these prefix shortcuts mean Shift + letter. `Super+L` locks the session.+On the installed system's empty home, Enter starts OpenCode. Super+n starts New+Harness, Super+t opens a shell directly, Super+m connects a computer, Super+w+opens Wi-Fi and Super+l locks the session. These require no Shift or prefix.+The shared TUI shortcuts still work: Ctrl+b, then Shift+n/t/w for the corresponding+actions. Ordinary hn on macOS and other Linux distributions retains its usual UI.Recovery remains available through another console or the USB; the owner retainsnormal Linux administrator control.## Updates and recoveryPreview 5 prepares hn/CLI releases automatically and shows a small bottom-bar-notice. `Super+U` opens Updates; Enter activates an available runtime and+notice. `Super+u` opens Updates; Enter activates an available runtime andreconnects the screen without a computer reboot. **R** restores the previousruntime. System updates use **S**, ask for the account password, retain acheckpoint and offer a restart when ready. Neither channel automaticallydiff --git a/os/installer.py b/os/installer.pyindex 24f7be8c1..e08e62745 100644--- a/os/installer.py+++ b/os/installer.py@@ -8,12 +8,14 @@ from datetime import datetime, timezoneimport hashlibimport jsonimport os+import pwdfrom pathlib import Pathimport reimport shleximport shutilimport subprocessimport sys+import tempfileimport timeMIN_DISK_BYTES = 12 * 1024**3@@ -155,6 +157,58 @@ def preflight(config, source):return kernel+def trial_command(action, source, account, destination_fd=None):+ # Project paths are user-controlled. Read and write them without installer+ # privileges; a symlink/race must never let the installer copy a root secret.+ command = ['/usr/bin/python3', '/usr/lib/harness-os/trial_projects.py', action, str(source)]+ descriptors = ()+ if destination_fd is not None:+ command += ['--destination-fd', str(destination_fd)]+ descriptors = (destination_fd,)+ result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=COMMAND_LOG,+ user=account.pw_uid, group=account.pw_gid, extra_groups=[],+ pass_fds=descriptors, env={'PATH': '/usr/bin', 'LANG': 'C.UTF-8'})+ return json.loads(result.stdout)+++def trial_source(config):+ if not Path('/etc/harness-live').is_file():+ return None+ account = pwd.getpwnam('me')+ source = Path(account.pw_dir) / 'Projects'+ if not source.exists():+ return None+ required = trial_command('size', source, account)['bytes']+ available = int(selected_disk(config)['size']) - 5 * 1024**3+ if required > available:+ raise ValueError('This disk needs more space for your trial projects. Choose a larger disk or save the projects elsewhere first.')+ return source, account+++def preserve_trial(trial, target, home):+ if trial is None:+ return None+ source, account = trial+ # 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.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)+ try:+ 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')+ 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')+ detail.chmod(0o600)+ return {key: value for key, value in receipt.items() if key != 'entries'}++def install(config, source, target, progress=None):report = progress or (lambda message: print(message, flush=True))validate_config(config)@@ -168,6 +222,7 @@ def install(config, source, target, progress=None):raise ValueError('Explicit confirmation of the exact disk is required.')report('Checking installation files…')kernel = preflight(config, source)+ trial = trial_source(config)selected_disk(config)started = time.monotonic()disk = config['disk']@@ -227,7 +282,8 @@ 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. No live passwords, SSH keys or sessions are copied.+ # 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','etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh']:@@ -243,7 +299,10 @@ def install(config, source, target, progress=None):write(target, f'/var/lib/systemd/linger/{config["username"]}', '')home = target / 'home' / config['username'](home / 'Projects').mkdir(exist_ok=True)- chroot(target, 'chown', '-R', f"{config['username']}:{config['username']}", f"/home/{config['username']}")+ if trial is not None:+ report('Keeping your trial projects…')+ trial_receipt = preserve_trial(trial, target, home)+ chroot(target, 'chown', '-Rh', f"{config['username']}:{config['username']}", f"/home/{config['username']}")write(target, '/etc/sudoers.d/10-harness', '%wheel ALL=(ALL:ALL) ALL\n', 0o440)write(target, '/etc/hostname', config['hostname'] + '\n')write(target, '/etc/hosts', f"127.0.0.1 localhost\n::1 localhost\n127.0.1.1 {config['hostname']}\n")@@ -306,6 +365,8 @@ def install(config, source, target, progress=None):receipt = {'version': lock['version'], 'installed_at': datetime.now(timezone.utc).isoformat(),'duration_seconds': round(time.monotonic() - started, 3), 'encrypted': config['encrypt'],'disk_bytes': selected_size(config), 'root_uuid': root_uuid, 'boot_uuid': boot_uuid}+ if trial_receipt is not None:+ receipt['trial_projects'] = trial_receiptwrite(target, '/var/lib/harness-os/install.json', json.dumps(receipt, indent=2) + '\n')report('Finishing installation…')run('sync')diff --git a/os/live_update.py b/os/live_update.pyindex 3fb00e566..44d67d37a 100644--- a/os/live_update.py+++ b/os/live_update.py@@ -255,7 +255,7 @@ def prune():def check(feeds=None, progress=lambda _: None, force_system=False):with locked():if RESTART_REQUIRED.exists():- notice(('Restart ready' if read(RESTART_REQUIRED, {}).get('status') == 'ready' else 'System update needs attention') + ' · Super+U')+ notice(('Restart ready' if read(RESTART_REQUIRED, {}).get('status') == 'ready' else 'System update needs attention') + ' · Super+u')return Falserecover_interrupted()current = selected()@@ -333,7 +333,7 @@ def check(feeds=None, progress=lambda _: None, force_system=False):write(STATE / 'check.json', {'checked_at': time.time(), 'errors': errors})available = ready is not None and ready != currentsystem = check_system(force_system) if feeds is None else {}- notice('Update ready · Super+U' if available or system.get('available') else '')+ notice('Update ready · Super+u' if available or system.get('available') else '')prune()if errors and not available:raise ValueError('Could not check for updates. Connect to the internet and try again.')@@ -438,7 +438,7 @@ def apply(rollback=False):select(previous)write(STATE / 'transaction.json', {'status': 'failed', 'previous': str(previous)})restart(candidate['cli'] != old['cli'])- notice('Update failed · Super+U')+ notice('Update failed · Super+u')raisewrite(STATE / 'applied.json', {'previous': str(previous), 'current': str(target), 'at': time.time()})if rollback:diff --git a/os/lock.json b/os/lock.jsonindex d6e958fc8..2bf264579 100644--- a/os/lock.json+++ b/os/lock.json@@ -1,8 +1,9 @@{- "version": "0.1.0-preview.6",+ "version": "0.1.0-preview.7","arch_snapshot": "2026/10/01","architecture": "x86_64","upgrades_from": [+ {"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/onboarding.py b/os/onboarding.pynew file mode 100644index 000000000..397787f7d--- /dev/null+++ b/os/onboarding.py@@ -0,0 +1,93 @@+#!/usr/bin/env python3+"""The USB's short network step; the real agent owns the workspace afterwards."""+import curses+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':+ 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.+ continue+ 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)+ except (OSError, subprocess.TimeoutExpired):+ pass+ os.execv('/usr/bin/hn-os', ['hn-os', 'try'])+++if __name__ == '__main__':+ welcome()diff --git a/os/root/etc/skel/.config/opencode/AGENTS.md b/os/root/etc/skel/.config/opencode/AGENTS.mdnew file mode 100644index 000000000..e77ebdc65--- /dev/null+++ b/os/root/etc/skel/.config/opencode/AGENTS.md@@ -0,0 +1,13 @@+# Harness++This computer runs Harness, a Linux operating system built by agents, for agents.++Before answering questions about Harness, its shortcuts, multiple agents,+connected computers, installation or system tools, read+`/usr/share/harness-os/guide.md`. It points to the complete shipped TUI reference+and explains how to discover the current bindings. Read the current file instead+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`.diff --git a/os/root/etc/skel/.config/opencode/opencode.json b/os/root/etc/skel/.config/opencode/opencode.jsonnew file mode 100644index 000000000..b0113fbf9--- /dev/null+++ b/os/root/etc/skel/.config/opencode/opencode.json@@ -0,0 +1,9 @@+{+ "$schema": "https://opencode.ai/config.json",+ "update": "disable",+ "permissions": [+ { "action": "external_directory", "resource": "/usr/share/harness-os/*", "effect": "allow" },+ { "action": "read", "resource": "/usr/share/harness-os/*", "effect": "allow" },+ { "action": "edit", "resource": "/usr/share/harness-os/*", "effect": "deny" }+ ]+}diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harnessindex 542b91dba..0826e56b0 100644--- a/os/root/usr/bin/harness+++ b/os/root/usr/bin/harness@@ -5,6 +5,9 @@ if [ "${1:-}" = hardware ]; thenfiif [ "${1:-}" = install ]; thenshift+ if [ "$#" = 0 ] && [ "$(id -u)" != 0 ]; then+ exec /usr/lib/harness-os/open-install+ fiexec /usr/bin/python3 /usr/lib/harness-os/install.py "$@"fiif [ "${1:-}" = upgrade ]; thendiff --git a/os/root/usr/lib/NetworkManager/dispatcher.d/50-harness-network b/os/root/usr/lib/NetworkManager/dispatcher.d/50-harness-networknew file mode 100755index 000000000..eb0310530--- /dev/null+++ b/os/root/usr/lib/NetworkManager/dispatcher.d/50-harness-network@@ -0,0 +1,13 @@+#!/bin/sh+# Publish a tiny state file on network events; no extra resident network monitor.+set -eu+state=$(LC_ALL=C nmcli -t -f STATE general)+temporary=$(mktemp /run/harness-network.XXXXXX)+trap 'rm -f "$temporary"' EXIT+if [ "$state" = connected ]; then+ printf '%s\n' connected > "$temporary"+else+ printf '%s\n' offline > "$temporary"+fi+chmod 644 "$temporary"+mv -f "$temporary" /run/harness-networkdiff --git a/os/root/usr/lib/harness-os/open-install b/os/root/usr/lib/harness-os/open-installnew file mode 100644index 000000000..c2f9d7dca--- /dev/null+++ b/os/root/usr/lib/harness-os/open-install@@ -0,0 +1,5 @@+#!/bin/sh+# Agent requests, compositor keys and the dock all open the same local form.+set -eu+[ -f /etc/harness-live ] || { printf '%s\n' 'Installation is available from the Harness USB.' >&2; exit 1; }+exec hn os-action installdiff --git a/os/root/usr/lib/harness-os/open-wifi b/os/root/usr/lib/harness-os/open-wifinew file mode 100644index 000000000..84cb8e27f--- /dev/null+++ b/os/root/usr/lib/harness-os/open-wifi@@ -0,0 +1,3 @@+#!/bin/sh+set -eu+exec hn os-action wifidiff --git a/os/root/usr/share/harness-os/AGENTS.md b/os/root/usr/share/harness-os/AGENTS.mdindex 676d55582..7919a6243 100644--- a/os/root/usr/share/harness-os/AGENTS.md+++ b/os/root/usr/share/harness-os/AGENTS.md@@ -5,12 +5,12 @@ for the current task, and use terminal output, diffs and tests to review the worOpen `hn-browser URL` only when a browser helps. Add tools and services when thecurrent task needs them; run extra services on demand unless the task needs thempersistently. Keep the desktop shell, launcher and panels absent unless the user-requests that interface. Open a new terminal immediately with Ctrl+B, then T. No agent or project setup+requests that interface. Open a new terminal immediately with Ctrl+b, then Shift+t. No agent or project setupis required.## System operations-- `Super+U` opens Updates inside hn; `harness updates` is the shell equivalent.+- `Super+u` opens Updates inside hn; `harness updates` is the shell equivalent.The user timer checks hn and CLI releases and prepares verified downloads.Activation is explicit. An hn-only change restarts its screen, keeping terminalowners and agents alive. System packages use the separate checkpointed action.@@ -61,8 +61,8 @@ is required.- npm installs into `~/.local`. The initial npm configuration permits the vendorinstall scripts for Claude Code, Codex and OpenCode. When another package needsan install script, approve that package explicitly; keep npm's other defaults.-- `Super+B` opens/focuses Chromium or returns to hn; `Super+Enter` focuses hn;- `Super+L` locks the screen. `sudo systemctl poweroff` shuts down cleanly.+- `Super+b` opens/focuses Chromium or returns to hn; `Super+Enter` focuses hn;+ `Super+l` locks the screen. `sudo systemctl poweroff` shuts down cleanly.- On supported NVIDIA Turing and newer GPUs, including RTX 4090/5090 and RTX 6000generations, the LTS-kernel packages are `nvidia-open-lts nvidia-utils`.Install both from the same repository snapshot, regenerate initramfs withdiff --git a/os/root/usr/share/harness-os/guide.md b/os/root/usr/share/harness-os/guide.mdnew file mode 100644index 000000000..fe28cef07--- /dev/null+++ b/os/root/usr/share/harness-os/guide.md@@ -0,0 +1,128 @@+# Helping someone use Harness++Harness is a Linux operating system built by agents, for agents. The user works in the+Harness terminal interface (`hn`). Each agent has its own conversation, project+and pane. A browser is available when viewing web content or graphical work helps.+This is a full Arch-based OS, with ordinary development tools installed as needed.++## Read the computer before advising++- `/etc/harness-live` exists only while running from the USB. Installation actions+ belong to that session, never to ordinary Harness on macOS or another Linux.+- `/usr/share/harness-os/lock.json` identifies the image. `hn --version` identifies+ the running TUI, which may have received a newer update independently.+- The complete shipped TUI reference is+ `/usr/share/harness-os/guide/tui.md`. Read the relevant sections before answering+ questions about features. Its source revision is in `guide/source.json`.+- `hn list-keys` reports the actual bindings, including the user's changes.+ `hn list-commands` reports supported commands. Prefer those live results when a+ newer TUI differs from the bundled reference. Do not substitute desktop-app+ Cmd shortcuts for terminal bindings.+- OS Super bindings are in `/usr/share/harness-os/labwc/rc.xml`; they are handled+ by the compositor and will not appear in `hn list-keys`.+- Read `/usr/share/harness-os/AGENTS.md` before changing system configuration.+ Do not describe planned hardware support as physically tested support.++## First conversation and installation++Help the user accomplish something small: build a page, fix code, explore a repo,+or ask about Harness. Answer directly; offer the relevant next action. The USB+Install dock already keeps installation visible, so do not repeat a sales pitch+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.+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.+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.+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.++## Multiple agents, panes and tabs++Use **New Harness** to start another agent; use **New terminal** for a shell+immediately, without an agent/project/task form. A pane shows one harness or+terminal. A tab groups panes. Different agents can work on different projects, or+on separate worktrees of the same repository. Explain file conflicts before+putting agents on the same working files. Closing a pane removes its view;+stopping a harness ends its running work. These are different actions.++OpenCode is bundled. Other supported agents can be installed when selected and+may require provider sign-in or an API key. Model availability, subscriptions and+free offerings are controlled by the provider. Keep OpenCode's default model+selection; never promise unlimited free access or pin a particular free model.++Useful terminal defaults (verify with `hn list-keys` if customized):++| Keys | Action |+| --- | --- |+| Ctrl+b, then Shift+n | New Harness |+| Ctrl+b, then Shift+t | New terminal |+| Ctrl+b, then s | Find harnesses across connected computers |+| Ctrl+b, then c | New tab |+| Ctrl+b, then n / p | Next / previous tab |+| Ctrl+b, then o / arrow | Next pane / pane in that direction |+| Ctrl+b, then z | Zoom or restore the focused pane |+| Ctrl+b, then % / " | Split right / below with a terminal |+| Ctrl+b, then a | Next harness needing attention |+| Ctrl+b, then Shift+a | All harnesses needing attention |+| Ctrl+b, then Shift+b | Broadcast a message to the tab |+| Ctrl+b, then @ | Machines |+| Ctrl+b, then Shift+s | Harness Store |+| Ctrl+b, then ? | Key reference |+| Ctrl+b, then : | Command prompt |+| Ctrl+b, then [ | Scrollback/copy mode |++Ctrl+b is a prefix: release it, then press the next key.+Each agent also owns its own keys while its pane has focus. Shift+Enter inserts a+new line in compatible agent prompts. Do not intercept agent shortcuts needlessly.++## Multiple computers++The **Connect a computer** action opens Harness's existing connection flow.+This computer works without a Harness account. Connecting other computers uses+the existing sign-in/link flow. If signed out, choose **Sign in on this computer**,+complete the normal sign-in flow, then open **Connect a computer** again.+**Set up another computer** explains the other computer's setup. Guide the user there rather than+collecting passwords in chat. The other computer needs Harness running and its+connection configured. A sleeping/offline computer cannot run a new task for us.++After linking, choose the destination computer and project in New Harness, or+open an existing harness through the machines/harnesses search. Work executes on+that computer: paths, tools, GPUs and files belong to it. The same path string on+two computers is not a shared folder. Connecting does not migrate projects.+Remote agents can sit beside local agents in one tab. Read the TUI reference's+machines, search and shared-session sections for exact interaction details.++## More of the TUI++The reference covers project/worktree choices, model selection, provider setup,+the Harness Store and viewers, search/filtering, questions and approvals, agent+states and activity, pause/resume/restart/clone, broadcasting, copy/clipboard,+layouts, appearance, key customization, session persistence and multiple clients.+Consult the relevant section and current command help instead of inventing a+shortcut. Do not assume several agent panes automatically collaborate or share+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.+- 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.+- Super+l locks the screen. Brightness and volume keys operate supported hardware.+- Super+u opens Updates after installation. Updates keep projects and running+ work; flashing another USB is not the everyday update workflow.++These shortcuts require no Shift and no Ctrl+b prefix. Super is the Windows-logo key on a PC keyboard and the Command key on a Mac+keyboard running this OS. These are OS bindings, not ordinary macOS bindings.+Use `hn-browser URL` to inspect a website. Agents remain the primary work surface.+For Wi-Fi, use `hn-os wifi`; passwords stay in its masked system form. For+hardware, drivers, packages, updates and recovery, follow the system guide above.diff --git a/os/root/usr/share/harness-os/labwc/rc.xml b/os/root/usr/share/harness-os/labwc/rc.xmlindex 6fde89d62..6b585b01c 100644--- a/os/root/usr/share/harness-os/labwc/rc.xml+++ b/os/root/usr/share/harness-os/labwc/rc.xml@@ -6,7 +6,7 @@<desktops><number>1</number><popupTime>0</popupTime></desktops><keyboard><repeatRate>35</repeatRate><repeatDelay>250</repeatDelay>- <!-- No default desktop shortcuts. Super+B is run-or-raise, then back to hn. -->+ <!-- No default desktop shortcuts. Super+b is run-or-raise, then back to hn. --><keybind key="W-b"><action name="If"><query identifier="chromium*" />@@ -21,6 +21,26 @@<action name="Execute" command="/usr/lib/harness-os/open-updates" /><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind>+ <keybind key="W-i">+ <action name="Execute" command="/usr/lib/harness-os/open-install" />+ <action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action>+ </keybind>+ <keybind key="W-w">+ <action name="Execute" command="/usr/lib/harness-os/open-wifi" />+ <action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action>+ </keybind>+ <keybind key="W-n">+ <action name="Execute" command="hn os-action new" />+ <action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action>+ </keybind>+ <keybind key="W-t">+ <action name="Execute" command="hn os-action terminal" />+ <action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action>+ </keybind>+ <keybind key="W-m">+ <action name="Execute" command="hn os-action connect" />+ <action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action>+ </keybind><keybind key="XF86MonBrightnessUp"><action name="Execute" command="brightnessctl set +5%" /></keybind><keybind key="XF86MonBrightnessDown"><action name="Execute" command="brightnessctl set 5%-" /></keybind><keybind key="XF86AudioRaiseVolume"><action name="Execute" command="wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%+ -l 1" /></keybind>diff --git a/os/root/usr/share/harness-os/tmux-live.conf b/os/root/usr/share/harness-os/tmux-live.confindex 54feb2d97..ef097967f 100644--- a/os/root/usr/share/harness-os/tmux-live.conf+++ b/os/root/usr/share/harness-os/tmux-live.conf@@ -1,4 +1,4 @@# Direct system actions remain available while trying an agent from USB.source-file /usr/share/harness-os/tmux.confunbind U-bind I new-window -n Install 'sudo /usr/bin/harness install'+bind I os-action installdiff --git a/os/root/usr/share/harness-os/tmux.conf b/os/root/usr/share/harness-os/tmux.confindex 83c158baa..1e5d40728 100644--- a/os/root/usr/share/harness-os/tmux.conf+++ b/os/root/usr/share/harness-os/tmux.conf@@ -2,7 +2,7 @@unbind dunbind Dunbind C-z-bind W new-window -n Wi-Fi '/usr/bin/hn-os wifi'+bind W os-action wifibind U new-window -n Updates '/usr/bin/harness updates'set -g status-right '#{@harness-update} "#H" %H:%M'set -g status-right-length 60diff --git a/os/tests/fast_update_vm.py b/os/tests/fast_update_vm.pyindex ecaf249b0..3ea9066c2 100644--- a/os/tests/fast_update_vm.py+++ b/os/tests/fast_update_vm.py@@ -53,13 +53,16 @@ def exercise(vm, fixture, host_url):vm.command('cat /proc/sys/kernel/random/boot_id > /tmp/fast-original-boot')vm.command('mkdir -p ~/.config/systemd/user/harness-update.service.d ~/.config/systemd/user/harness-update.timer.d')put(vm, '/tmp/update-service.conf', '[Service]\nExecStart=\nExecStart=/usr/bin/python3 /usr/lib/harness-os/live_update.py check --feeds /tmp/fast-updates/feeds-hn.json\n')- put(vm, '/tmp/update-timer.conf', '[Timer]\nOnStartupSec=\nOnUnitInactiveSec=\nRandomizedDelaySec=0\nOnActiveSec=1s\n')+ # systemd's default AccuracySec=1min can coalesce the one-second fixture+ # beyond its deadline. Keep the real timer path, with explicit test accuracy.+ put(vm, '/tmp/update-timer.conf', '[Timer]\nOnStartupSec=\nOnUnitInactiveSec=\nRandomizedDelaySec=0\nAccuracySec=100ms\nOnActiveSec=1s\n')vm.command('cp /tmp/update-service.conf ~/.config/systemd/user/harness-update.service.d/fixture.conf; ''cp /tmp/update-timer.conf ~/.config/systemd/user/harness-update.timer.d/fixture.conf; ''systemctl --user daemon-reload; systemctl --user restart harness-update.timer')state = '~/.local/state/harness-os/updates'vm.command('for n in $(seq 1 120); do test -s ' + state + '/ready.json && exit 0; sleep .5; done; '- 'journalctl --user -u harness-update --no-pager; exit 1', timeout=75)+ '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']vm.command('test ! -e ' + state + '/current')diff --git a/os/tests/test_first_use.py b/os/tests/test_first_use.pyindex 4638cf5e2..aa9040bcd 100644--- a/os/tests/test_first_use.py+++ b/os/tests/test_first_use.py@@ -13,6 +13,18 @@ loader.exec_module(hn_os)class FirstUse(unittest.TestCase):+ def test_global_agent_guide_is_added_without_replacing_personal_instructions(self):+ with tempfile.TemporaryDirectory() as temp, patch.dict(hn_os.os.environ, {'XDG_CONFIG_HOME': temp}):+ guide = Path(temp) / 'opencode/AGENTS.md'+ hn_os.prepare_opencode_guidance()+ self.assertTrue(guide.is_symlink())+ self.assertEqual(guide.readlink(), Path('/usr/share/harness-os/guide.md'))+ hn_os.prepare_opencode_guidance()+ guide.unlink()+ guide.write_text('My own instructions.\n')+ hn_os.prepare_opencode_guidance()+ self.assertEqual(guide.read_text(), 'My own instructions.\n')+def test_old_cpu_gets_an_explanation_before_network_setup_or_agent_launch(self):for cpu, ready in [('flags : sse sse2 ssse3\n', False), ('flags : sse4_2\n', True),('Features : fp asimd\n', True)]:diff --git a/os/tests/test_onboarding.py b/os/tests/test_onboarding.pynew file mode 100644index 000000000..928ceb52d--- /dev/null+++ b/os/tests/test_onboarding.py@@ -0,0 +1,76 @@+import importlib.util+import os+from pathlib import Path+import subprocess+import unittest+from unittest.mock import patch++spec = importlib.util.spec_from_file_location('onboarding', Path(__file__).resolve().parents[1] / 'onboarding.py')+onboarding = importlib.util.module_from_spec(spec)+spec.loader.exec_module(onboarding)+++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_offline_install_opens_native_form_without_starting_an_agent(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.os, 'execv') as execute:+ with self.assertRaises(KeyboardInterrupt):+ onboarding.welcome()+ command.assert_called_once_with(['hn', 'os-action', 'install'], check=True, timeout=15)+ 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, \+ 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()++ 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_install_launch_failure_keeps_a_recoverable_network_screen(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:+ with self.assertRaises(KeyboardInterrupt):+ onboarding.welcome()+ self.assertIn('Could not open Install', form.call_args.args[1])+ execute.assert_not_called()+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_package.py b/os/tests/test_package.pyindex adc718482..6c517210d 100644--- a/os/tests/test_package.py+++ b/os/tests/test_package.py@@ -13,6 +13,37 @@ spec.loader.exec_module(package)class PackageIdentity(unittest.TestCase):+ def test_new_accounts_discover_the_packaged_guide_without_model_overrides(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp)+ runtime = base / 'runtime'+ runtime.mkdir()+ for name in ['harness-tui', 'cli.js', 'notify.mjs']:+ (runtime / name).write_bytes(b'runtime fixture')+ destination = base / 'stage'+ with patch.object(package, 'validate_runtime', return_value={'source_commit': 'a' * 40}):+ identity = package.stage(Path(__file__).resolve().parents[2], runtime, destination, 'a' * 40)+ config = destination / 'etc/skel/.config/opencode'+ self.assertFalse((config / 'AGENTS.md').is_symlink())+ self.assertIn('/usr/share/harness-os/guide.md', (config / 'AGENTS.md').read_text())+ self.assertIn('Super+n', (destination / 'usr/share/harness-os/guide.md').read_text())+ settings = json.loads((config / 'opencode.json').read_text())+ self.assertEqual(settings['update'], 'disable')+ self.assertFalse(set(settings) & {'model', 'provider', 'providers', 'instructions'})+ self.assertEqual(settings['permissions'], [+ {'action': 'external_directory', 'resource': '/usr/share/harness-os/*', 'effect': 'allow'},+ {'action': 'read', 'resource': '/usr/share/harness-os/*', 'effect': 'allow'},+ {'action': 'edit', 'resource': '/usr/share/harness-os/*', 'effect': 'deny'},+ ], 'Only the packaged reference directory gets a read exception, never arbitrary filesystem access')+ # Validate the real staged package with the same guard that protects+ # installed systems, not only an isolated archive fixture.+ output = base / 'harness-os.pkg.tar.gz'+ package.archive_package(destination, output, 'pkgname = harness-os\npkgver = 1-1\narch = x86_64\n', 123456)+ spec = importlib.util.spec_from_file_location('runtime_package_check', Path(__file__).parents[1] / 'runtime_update.py')+ updater = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(updater)+ updater.inspect_package(output, '1-1', identity)+def test_same_source_is_byte_identical_across_build_times_and_output_names(self):with tempfile.TemporaryDirectory() as temp:root = Path(temp) / 'stage'diff --git a/os/tests/test_publication.py b/os/tests/test_publication.pyindex f2a26555a..cabbb5eb9 100644--- a/os/tests/test_publication.py+++ b/os/tests/test_publication.py@@ -114,7 +114,8 @@ class PublicationGuards(unittest.TestCase):incomplete[0]['checks'] = [row for row in incomplete[0]['checks'] if not row.startswith('On-demand')]with self.assertRaises(ValueError):publish.validate_receipts(manifest, incomplete)- for prefix, index in [('USB Enter', 0), ('USB first agent', 0), ('Bundled OpenCode', 0), ('Harness unlock', 1), ('Claude Code', 0)]:+ for prefix, index in [('USB opens network', 0), ('USB first agent', 0), ('Bundled OpenCode loads', 0),+ ('Bundled OpenCode starts', 0), ('Agent-created USB trial', 0), ('Harness unlock', 1), ('Claude Code', 0)]:incomplete = copy.deepcopy(receipts)incomplete[index]['checks'] = [row for row in incomplete[index]['checks'] if not row.startswith(prefix)]with self.subTest(missing=prefix), self.assertRaises(ValueError):diff --git a/os/tests/test_trial_projects.py b/os/tests/test_trial_projects.pynew file mode 100644index 000000000..07b142515--- /dev/null+++ b/os/tests/test_trial_projects.py@@ -0,0 +1,72 @@+import hashlib+import importlib.util+import os+from pathlib import Path+import tempfile+import unittest+from unittest.mock import patch++spec = importlib.util.spec_from_file_location('trial_projects', Path(__file__).resolve().parents[1] / 'trial_projects.py')+trial = importlib.util.module_from_spec(spec)+spec.loader.exec_module(trial)+++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 / 'game/.git').mkdir(parents=True)+ (source / 'empty').mkdir()+ script = source / 'game/run'+ script.write_bytes(b'#!/bin/sh\nexit 0\n')+ script.chmod(0o751)+ (source / 'game/.git/HEAD').write_text('ref: refs/heads/main\n')+ (source / 'game/asset').write_bytes(bytes(range(256)) * 16)+ (source / 'current').symlink_to('game')+ (source / 'missing').symlink_to('future')+ (base / 'credentials').write_text('never copy this home file')+ receipt = trial.transfer(source, target)+ self.assertEqual((target / 'game/asset').read_bytes(), (source / 'game/asset').read_bytes())+ self.assertEqual((target / 'game/.git/HEAD').read_text(), 'ref: refs/heads/main\n')+ self.assertEqual((target / 'game/run').stat().st_mode & 0o777, 0o751)+ self.assertEqual((target / 'game/run').stat().st_mtime_ns, script.stat().st_mtime_ns)+ self.assertEqual(os.readlink(target / 'current'), 'game')+ self.assertEqual(os.readlink(target / 'missing'), 'future')+ self.assertTrue((target / 'empty').is_dir())+ self.assertFalse((target / 'credentials').exists())+ self.assertEqual(receipt['bytes'], trial.size(source))+ self.assertEqual(receipt['entries']['game/asset']['sha256'], hashlib.sha256((source / 'game/asset').read_bytes()).hexdigest())++ 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.mkdir()+ outside.mkdir()+ (outside / 'secret').write_text('outside project')+ (source / 'external').symlink_to(outside, target_is_directory=True)+ receipt = trial.transfer(source, base / 'installed')+ self.assertEqual(receipt['entries'], {'external': {'link': str(outside)}})+ self.assertEqual(receipt['bytes'], 0)+ with self.assertRaisesRegex(ValueError, 'ordinary directory'):+ trial.size(source / 'external')++ def test_special_files_fail_preflight_and_copy_without_hanging(self):+ with tempfile.TemporaryDirectory() as temp:+ source = Path(temp) / 'Projects'+ source.mkdir()+ os.mkfifo(source / 'pipe')+ with self.assertRaisesRegex(ValueError, 'special file'):+ trial.size(source)+ with self.assertRaisesRegex(ValueError, 'Close the service'):+ trial.transfer(source, Path(temp) / 'installed')++ def test_unreadable_directory_is_an_error_not_silent_data_loss(self):+ error = PermissionError('private directory')+ with self.assertRaises(PermissionError):+ trial.walk_error(error)+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_vm_control.py b/os/tests/test_vm_control.pynew file mode 100644index 000000000..692de840e--- /dev/null+++ b/os/tests/test_vm_control.py@@ -0,0 +1,37 @@+import io+import json+from pathlib import Path+import importlib.util+import unittest+from unittest.mock import Mock, patch++spec = importlib.util.spec_from_file_location('os_vm', Path(__file__).with_name('vm.py'))+vm_module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(vm_module)+++class MonitorCommands(unittest.TestCase):+ def test_network_device_name_is_sent_as_a_qmp_argument(self):+ vm = vm_module.VM.__new__(vm_module.VM)+ vm.qmp = Mock()+ vm.qmp_file = io.BytesIO(b'{"return": {}, "id": "network-check"}\n')+ with patch.object(vm_module.uuid, 'uuid4', return_value=Mock(hex='network-check')):+ self.assertEqual(vm.monitor('set_link', name='hnnet', up=False), {})+ sent = json.loads(vm.qmp.sendall.call_args.args[0])+ self.assertEqual(sent, {'execute': 'set_link', 'arguments': {'name': 'hnnet', 'up': False}, 'id': 'network-check'})++ def test_ocr_click_maps_the_lowest_control_back_to_the_real_frame(self):+ words = 'left\ttop\twidth\theight\ttext\n124\t224\t100\t24\tInstall\n'+ words += '492\t1576\t120\t28\tInstall\n'+ self.assertEqual(vm_module.control_point(words, 'Install', 1280, 800, 2, 24),+ (round(264 * 32767 / 1279), round(783 * 32767 / 799)))++ def test_missing_or_out_of_frame_controls_never_generate_a_click(self):+ for words in ['left\ttop\twidth\theight\ttext\n0\t0\t8\t8\tOther\n',+ 'left\ttop\twidth\theight\ttext\n0\t0\t8\t8\tInstall\n']:+ with self.assertRaises(AssertionError):+ vm_module.control_point(words, 'Install', 1280, 800, 2, 24)+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/vm.py b/os/tests/vm.pyindex ca54928ef..824bf1e7b 100644--- a/os/tests/vm.py+++ b/os/tests/vm.py@@ -7,6 +7,7 @@ to QEMU. Screenshots, serial logs, timings and checks survive every failure.from __future__ import annotationsimport argparseimport base64+import csvimport hashlibimport ioimport json@@ -24,6 +25,17 @@ import timeimport uuid+def control_point(words, word, width, height, scale, border):+ rows = [r for r in csv.DictReader(io.StringIO(words), delimiter='\t')+ if r.get('text', '').strip('[]').lower() == word.lower()]+ assert rows, f'The visible screen has no {word} control'+ row = max(rows, key=lambda r: int(r['top'])) # The dock is the lowest instance.+ x = (int(row['left']) + int(row['width']) / 2 - border) / scale+ y = (int(row['top']) + int(row['height']) / 2 - border) / scale+ assert 0 <= x < width and 0 <= y < height, 'OCR control lies outside the actual screen'+ return round(x * 32767 / (width - 1)), round(y * 32767 / (height - 1))++class VM:def __init__(self, folder, iso, firmware, memory, live_transport='cdrom', cpu=None, video='virtio-vga', audio=False):self.folder, self.iso, self.firmware, self.memory = folder, iso, firmware, memory@@ -67,10 +79,11 @@ class VM:self.acceleration = accelerationargs = ['qemu-system-x86_64', '-accel', acceleration, '-m', str(self.memory), '-smp', '2','-cpu', self.cpu or ('host' if acceleration == 'kvm' else 'max'), '-device', self.video,+ '-device', 'virtio-tablet-pci','-display', 'none', '-no-reboot','-drive', f'file={self.disk},format=qcow2,if=none,id=target','-device', f'virtio-blk-pci,drive=target,serial=HN_OS_TEST,bootindex={2 if live else 1}',- '-device', 'virtio-net-pci,netdev=net', '-netdev', 'user,id=net',+ '-device', 'virtio-net-pci,netdev=net,id=hnnet', '-netdev', 'user,id=net','-serial', f'unix:{self.control_path / "serial.sock"},server=on,wait=off','-qmp', f'unix:{self.control_path / "qmp.sock"},server=on,wait=off']if self.audio:@@ -114,9 +127,9 @@ class VM:time.sleep(0.1)raise TimeoutError(f'QEMU did not expose {name}')- def monitor(self, name, **arguments):+ def monitor(self, command, /, **arguments):identity = uuid.uuid4().hex- self.qmp.sendall((json.dumps({'execute': name, 'arguments': arguments, 'id': identity}) + '\n').encode())+ self.qmp.sendall((json.dumps({'execute': command, 'arguments': arguments, 'id': identity}) + '\n').encode())while True:result = json.loads(self.qmp_file.readline())if result.get('id') == identity:@@ -251,6 +264,32 @@ class VM:self.monitor('send-key', keys=[{'type': 'qcode', 'data': key} for key in keys], **{'hold-time': 100})time.sleep(0.12) # Release each key, including repeated password characters.+ def click_word(self, name, word):+ """Locate a visible control in a screenshot and send actual pointer input."""+ from PIL import Image, ImageOps+ self.screenshot(name)+ frame = self.folder / (name + '.png')+ # Small text against the screen edge needs a margin for OCR. Keep the+ # original framebuffer and the exact transform so clicks still target+ # the real control, never a hard-coded or inferred screen location.+ scale, border = 2, 24+ ocr_frame = self.folder / (name + '-ocr.png')+ with Image.open(frame) as image:+ width, height = image.size+ readable = ImageOps.invert(image.convert('L')).resize((width * scale, height * scale))+ ImageOps.expand(readable, border=border, fill=255).save(ocr_frame)+ words = subprocess.check_output(['tesseract', str(ocr_frame), 'stdout', '--psm', '11', 'tsv'],+ stderr=subprocess.DEVNULL, text=True, timeout=15)+ (self.folder / (name + '-ocr.txt')).write_text(words)+ x, y = control_point(words, word, width, height, scale, border)+ self.monitor('input-send-event', events=[+ {'type': 'abs', 'data': {'axis': 'x', 'value': x}},+ {'type': 'abs', 'data': {'axis': 'y', 'value': y}},+ ])+ for down in [True, False]:+ self.monitor('input-send-event', events=[{'type': 'btn', 'data': {'button': 'left', 'down': down}}])+ time.sleep(.15)+def type_probe(self, text):# Send display keyboard events, not hn's CLI input path. Probe commands# deliberately need only these unshifted US-layout characters.@@ -326,6 +365,16 @@ def check_console_fallback(vm, user, folder):'sleep 1; done; exit 1', timeout=75)vm.command('! pgrep -u 1000 -x labwc && ! pgrep -u 1000 -x foot')vm.command(user('/usr/lib/harness-os/wait-runtime'), timeout=160)+ # A process attached to tty1 is not yet its command endpoint. During+ # takeover the named socket can still belong to the departing renderer.+ # Wait for a reply from this VT's actual client before creating a pane.+ vm.command(user('sh -c ' + shlex.quote(+ 'for n in $(seq 1 60); do '+ 'p=$(hn display-message -p "#{client_pid}") || p=; '+ 'case "$p" in ""|*[!0-9]*) ;; *) '+ 'if test "$(readlink /proc/$p/fd/0)" = /dev/tty1; then '+ 'printf "HN_CONSOLE_READY=%s\\n" "$p"; exit 0; fi ;; esac; '+ 'sleep .25; done; exit 1')), timeout=75)vm.command('kill -0 "$(cat /tmp/hn-survivor.pid)"')probe = ('printf "Console input ready\\n"; touch /tmp/hn-console-input-ready; ''read -r answer; test "$answer" = ready && '@@ -342,6 +391,8 @@ def check_console_fallback(vm, user, folder):output, _ = vm.command('cat /home/me/.local/state/harness-os/display.log; ''ps -u 1000 -o pid,ppid,tty,comm; cat /dev/vcs1', check=False)(folder / 'console-fallback.log').write_text(output)+ output, _ = vm.command(user('hn hn-list-clients; hn show-messages'), check=False)+ (folder / 'console-client.log').write_text(output)vm.command('rm -f ' + override + '; systemctl restart [email protected]')vm.command(user("sh -c 'for n in $(seq 1 60); do systemctl --user is-active --quiet hn-screen && ""pgrep -x labwc >/dev/null && pgrep -x foot >/dev/null && exit 0; "@@ -357,17 +408,20 @@ def check_first_use(vm, user, folder):vm.command('nmcli networking off')version, _ = vm.command(user('/usr/bin/opencode --version'))(folder / 'bundled-opencode-version.txt').write_text(version)- vm.command('test ! -e /home/me/.config/opencode/opencode.json')- vm.keys('t')+ 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.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')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.keys('ret')vm.command('sleep 1; ! pgrep -u 1000 -x opencode')- # Enter is Install, including while the network is disabled.- vm.keys('ret')+ # 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.screenshot('01b-direct-install-offline')vm.keys('esc')@@ -381,8 +435,7 @@ def check_first_use(vm, user, folder):vm.keys('ret')vm.command('for n in $(seq 1 15); do ! pgrep -f ' + shlex.quote(installer_process) + ' && exit 0; sleep 1; done; exit 1', timeout=20)# New terminal is a shell immediately, without agent/project/task fields.- vm.keys('ctrl', 'b')- vm.keys('shift', 't')+ vm.keys('meta_l', 't')vm.type_probe('echo terminal-ready')vm.keys('ret')vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 20); do hn capture-pane -p | grep -qx terminal-ready && exit 0; sleep 1; done; exit 1')), timeout=30)@@ -409,11 +462,25 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shellvm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do ''hn list-panes -a -F "#{pane_id}" | grep -Fx ' + shlex.quote(pane.group(1)) +' >/dev/null || exit 0; sleep .25; done; exit 1')), timeout=15)+ vm.monitor('set_link', name='hnnet', up=True)vm.command('nmcli networking on; for n in $(seq 1 30); do test "$(nmcli -t -f STATE general)" = connected && exit 0; sleep 1; done; exit 1', timeout=40)- vm.keys('t')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')+ # 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)+ 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+ # documented global AGENTS.md carries instructions; the real conversation+ # below independently checks that the agent knows the Harness shortcuts.+ agent_config = json.loads(config_sources)+ assert isinstance(agent_config, list) and any(row.get('path') == '/home/me/.config/opencode' for row in agent_config), 'OpenCode did not discover its global configuration'+ instructions = vm.read_file('/home/me/.config/opencode/AGENTS.md')+ assert instructions == vm.read_file('/etc/skel/.config/opencode/AGENTS.md'), 'OpenCode global instructions differ from the packaged entry point'+ assert b'/usr/share/harness-os/guide.md' in instructions, 'OpenCode must discover the current packaged guide'vm.command('test ! -e /home/me/.config/opencode/plugin/launcher-register.js && test -s /home/me/.config/opencode/plugins/launcher-register/tui.js')screen, _ = vm.command(user('hn capture-pane -p'))(folder / 'bundled-opencode-screen.txt').write_text(screen)@@ -421,6 +488,38 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shelloutput, _ = vm.command(user('hn display-message -p "HN_FIRST_AGENT=#{pane_id}"'))agent_pane = re.search(r'HN_FIRST_AGENT=(%\d+)', output)assert agent_pane, 'The visible OpenCode must identify its actual pane'+ vm.keys('meta_l', 'n')+ time.sleep(1)+ vm.screenshot('01d-new-harness')+ vm.keys('esc')+ vm.keys('meta_l', 'm')+ time.sleep(1)+ vm.screenshot('01d-connect-computer')+ # Fresh USB users are signed out. The connection panel must lead to the+ # normal local sign-in flow, with a cancellable return to the trial.+ vm.type_probe('sign in')+ vm.keys('ret')+ login_process = '[/]usr/lib/harness/cli.mjs login'+ vm.command('for n in $(seq 1 20); do pgrep -u 1000 -f ' + shlex.quote(login_process) ++ ' >/dev/null && exit 0; sleep 1; done; exit 1', timeout=30)+ time.sleep(2)+ vm.screenshot('01d-connect-sign-in')+ vm.keys('ctrl', 'c')+ vm.command('for n in $(seq 1 20); do ! pgrep -u 1000 -f ' + shlex.quote(login_process) ++ ' >/dev/null && exit 0; sleep 1; done; exit 1', timeout=30)+ vm.keys('ret')+ time.sleep(1)+ # 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.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('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# into the visible agent and receive its answer, without a CLI/API shortcut.vm.type_probe('what is six times seven reply with digits only')@@ -433,6 +532,32 @@ if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shell(folder / 'first-opencode-interactive.txt').write_text(screen)vm.screenshot('01e-first-agent-reply')assert interactive_status == 0, 'The visible bundled agent must accept keyboard input and display its reply'+ # The real agent receives the local guide, knows both shortcut layers, and+ # creates work that the later offline installation must preserve.+ vm.type_probe('what are the os shortcuts for a new harness and connecting a computer and does ctrl b still work')+ vm.keys('ret')+ _, guide_status = vm.command(user('sh -c ' + shlex.quote(+ 'for n in $(seq 1 120); do hn capture-pane -p > /tmp/hn-first-guide.txt; '+ "grep -Eiq 'super[[:space:]]*\\+[[:space:]]*n' /tmp/hn-first-guide.txt && "+ "grep -Eiq 'super[[:space:]]*\\+[[:space:]]*m' /tmp/hn-first-guide.txt && exit 0; "+ 'sleep 1; done; exit 1')), timeout=140, check=False)+ (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')+ 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.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('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.'@@ -594,6 +719,7 @@ def main():user = lambda cmd: 'runuser -u "$(id -nu 1000)" -- env XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus ' + cmdtry:vm.start(live=True)+ vm.monitor('set_link', name='hnnet', up=False)vm.wait(r'root@[^\r\n]*[#] ')vm.shell_ready = Truevm.command('stty -echo')@@ -640,9 +766,11 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'output, _ = vm.command(user('hn-os measure'))(folder / 'live-measurement.txt').write_text(output)check_first_use(vm, user, folder)- result['checks'].append('USB Enter opens Install offline; Try opens network setup while disconnected; direct terminal accepts physical keyboard input')+ 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')+ result['checks'].append('Bundled OpenCode loads the local TUI guide, explains Super+n/m, creates a trial project, and opens the native installer on request')+ result['checks'].append('Super+n/m open the agent and machine controls; F10/Enter and an actual pointer click open the install dock action')result['checks'].append('Bundled OpenCode starts offline and its upstream-default clean-profile conversation returns the independently checked answer')vm.keys('meta_l', 'b')vm.command("for n in $(seq 1 45); do pgrep -x chromium >/dev/null && break; sleep 1; done; pgrep -x chromium", timeout=60)@@ -684,6 +812,8 @@ 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'))+ 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)result['checks'].append('Keyboard disk selection, encryption checkbox, masked password entry and a single Install action work on the guest terminal')@@ -693,6 +823,12 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'vm.start(live=False)unlock_delay = 100 if config['encrypt'] else 0vm.login_installed(config, unlock_delay=unlock_delay)+ saved_trial = vm.read_file('/home/me/Projects/usb-trial/index.html')+ 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')+ 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()+ result['checks'].append('Agent-created USB trial project survives offline installation and installed boot byte-for-byte')result['deliberate_unlock_delay_seconds'] = unlock_delayif unlock_delay:result['installed_unlock_prompt_seconds'] = vm.unlock_prompt_secondsdiff --git a/os/tools/build-package.py b/os/tools/build-package.pyindex 55947e902..07bf3d3ee 100644--- a/os/tools/build-package.py+++ b/os/tools/build-package.py@@ -42,6 +42,8 @@ def stage(source, runtime, destination, commit):special = {'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/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','os/live_update.py': 'usr/lib/harness-os/live_update.py',@@ -49,12 +51,18 @@ def stage(source, runtime, destination, commit):'os/hardware.py': 'usr/lib/harness-os/hardware.py','os/tools/hn-os': 'usr/bin/hn-os','os/lock.json': 'usr/share/harness-os/lock.json',+ 'tui/README.md': 'usr/share/harness-os/guide/tui.md',+ 'docs/naming-system.md': 'usr/share/harness-os/guide/naming.md',}for local, target in special.items():path = destination / targetpath.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(source / local, path)path.chmod(0o644)+ (destination / 'usr/share/harness-os/guide/source.json').write_text(+ json.dumps({'source_commit': commit, 'tui_reference': 'tui/README.md'}, indent=2) + '\n')+ # The regular skel AGENTS.md points OpenCode to the current packaged guide.+ # Archive symlinks outside their directory are rejected by the updater.library = destination / 'usr/lib/harness'library.mkdir(parents=True)for local, target in [('harness-tui', 'harness-tui'), ('cli.js', 'cli.mjs'), ('notify.mjs', 'notify.mjs')]:diff --git a/os/tools/hn-os b/os/tools/hn-osindex 6d9340382..eaedea3c9 100644--- a/os/tools/hn-os+++ b/os/tools/hn-os@@ -44,6 +44,17 @@ def opencode_cpu_ready():return True # The x86 instruction check does not apply to an ARM CPU.+def prepare_opencode_guidance():+ # Fresh accounts get this from skel. An older installation receives the+ # same guide on first use, without replacing personal instructions.+ config = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'opencode'+ config.mkdir(parents=True, exist_ok=True)+ try:+ (config / 'AGENTS.md').symlink_to('/usr/share/harness-os/guide.md')+ except FileExistsError:+ pass++def try_harness():if not opencode_cpu_ready():print('The bundled OpenCode needs a newer CPU (SSE4.2).')@@ -59,6 +70,7 @@ def try_harness():returnprojects = Path.home() / 'Projects'projects.mkdir(exist_ok=True)+ prepare_opencode_guidance()os.chdir(projects)os.execv('/usr/bin/opencode', ['opencode'])@@ -75,6 +87,8 @@ def main():if command == 'try':try_harness()return+ if command == 'welcome':+ os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/onboarding.py'])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.pyindex a5d05d919..69659d7f2 100644--- a/os/tools/inspect_image.py+++ b/os/tools/inspect_image.py@@ -31,13 +31,17 @@ def inspect(iso):return subprocess.check_output(['unsquashfs', '-cat', str(payload), path])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/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','usr/lib/harness-os/live_update.py': source / 'live_update.py','usr/lib/harness-os/release_update.py': source / 'release_update.py','usr/lib/harness-os/hardware.py': source / 'hardware.py','usr/bin/hn-os': source / 'tools/hn-os',- 'usr/share/harness-os/lock.json': source / 'lock.json'})+ 'usr/share/harness-os/lock.json': source / 'lock.json',+ 'usr/share/harness-os/guide/tui.md': source.parent / 'tui/README.md',+ 'usr/share/harness-os/guide/naming.md': source.parent / 'docs/naming-system.md'})for path, expected in files.items():assert read(path) == expected.read_bytes(), f'Payload does not match source: {path}'checked.append(path)@@ -51,6 +55,10 @@ def inspect(iso):for path in [*files, '', 'etc', 'usr', 'usr/bin', 'usr/lib/harness-os', 'usr/share/harness-os']:assert owners.get(path) == '0/0', f'Packaged system path is not owned by root: {path}'runtime = json.loads(read('usr/share/harness-os/runtime.json'))+ guide = json.loads(read('usr/share/harness-os/guide/source.json'))+ assert guide == {'source_commit': manifest['source_commit'], 'tui_reference': 'tui/README.md'}, 'Agent guide belongs to a different source'+ assert read('home/me/.config/opencode/AGENTS.md') == read('etc/skel/.config/opencode/AGENTS.md')+ assert read('home/me/.config/opencode/opencode.json') == read('etc/skel/.config/opencode/opencode.json')assert runtime == manifest['harness_inputs'] and runtime['source_commit'] == manifest['source_commit']assert not runtime['dirty'] and runtime['target'] == 'x86_64-unknown-linux-musl'for name, identity in runtime['files'].items():diff --git a/os/tools/publish-update.py b/os/tools/publish-update.pyindex c2ba87e98..c8e131491 100644--- a/os/tools/publish-update.py+++ b/os/tools/publish-update.py@@ -135,7 +135,7 @@ def main():if '404' not in result.stderr:raise ValueError('Cannot read the OS channel: ' + result.stderr)notes = output / 'channel-notes.md'- notes.write_text('Harness OS preview update metadata. The computer checks this channel automatically; open Updates with Super+U to install.\n')+ notes.write_text('Harness OS preview update metadata. The computer checks this channel automatically; open Updates with Super+u to install.\n')gh('release', 'create', CHANNEL, '--repo', REPO, '--target', manifest['source_commit'], '--draft', '--prerelease','--title', 'Harness OS preview updates', '--notes-file', notes)gh('release', 'upload', CHANNEL, '--repo', REPO, '--clobber', feed)diff --git a/os/tools/publish.py b/os/tools/publish.pyindex fe547381d..95747566e 100644--- a/os/tools/publish.py+++ b/os/tools/publish.py@@ -12,8 +12,10 @@ import timeimport zipfileREQUIRED_CHECKS = ['Live hn ready;', 'Wayland clipboard round trip',- 'USB Enter opens Install offline;',+ 'USB opens network setup; Super+i opens Install offline;','USB first agent conversation accepts physical keyboard input',+ 'Bundled OpenCode loads the local TUI guide',+ 'Agent-created USB trial project survives offline installation','Bundled OpenCode starts offline and its upstream-default clean-profile conversation','Keyboard disk selection, encryption checkbox, masked password entry and a single Install action','Browser starts only on shortcut', 'Dated package repositories are queryable',@@ -197,17 +199,17 @@ def main():reuse_note = ('Completed project sources were retained from ' + ', '.join(f'[run {source}](https://github.com/{args.repo}/actions/runs/{source})' for source in project_source_runs) +'. The game agent ran again; all four projects\' unit tests and independent acceptance checks reran on this exact image.') if project_source_runs else ''- notes.write_text(f'''Boot directly into hn. Open agents with Ctrl+B, then N. Super+B opens Chromium or returns to hn.+ notes.write_text(f'''Harness is a Linux operating system built by agents, for agents. Boot into the terminal, start another agent with Super+n, and open the browser with Super+b.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. On the USB welcome screen, press Enter to install or T to try Harness. Try opens Wi-Fi setup when needed, then bundled OpenCode with its upstream default settings. Ctrl+B then T opens a terminal directly; Ctrl+B then I opens the installer from a live session. 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 ''}{'Interrupted full OS updates block ordinary package transactions until a full retry succeeds. Retrying keeps the original recovery checkpoint. This was exercised with a real failed repository refresh, blocked package upgrade, successful retry, and offline recovery. hn-os update upgrades Arch packages.' if update_retry else ''}-{'Super+U opens Updates. hn and CLI releases are prepared automatically; Enter activates an available runtime update. hn reconnects to the local tabs while agent processes keep running. System updates are a separate action in the same screen, with a checkpoint and a restart when you are ready. Neither channel automatically interrupts your work. Older preview 4 installations need the matching small bootstrap bundle once; routine updates do not require reflashing.' if in_place_updates else ''}+{'Super+u opens Updates. hn and CLI releases are prepared automatically; Enter activates an available runtime update. hn reconnects to the local tabs while agent processes keep running. System updates are a separate action in the same screen, with a checkpoint and a restart when you are ready. Neither channel automatically interrupts your work. Older preview 4 installations need the matching small bootstrap bundle once; routine updates do not require reflashing.' if in_place_updates else ''}BIOS/plain and UEFI/encrypted VM boot, clipboard, browser switching, offline installation and package-checkpoint recovery passed. The BIOS VM uses a Nehalem CPU profile without AVX2, starts bundled OpenCode, installs the other agent executables, installs a compiler on demand, builds C, and serves a local Node preview. See `validation.json` and `machine-evidence.zip` for the exact checks and measurements.diff --git a/os/trial_projects.py b/os/trial_projects.pynew file mode 100644index 000000000..4ec9e4a4b--- /dev/null+++ b/os/trial_projects.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""Copy saved USB projects as their owner, without copying the live account."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import stat+++def walk_error(error):+ raise error+++def transfer(source, destination):+ """Symlinks stay symlinks; special files and changing files stop the transfer."""+ if source.is_symlink() or not source.is_dir():+ raise ValueError('The USB Projects folder must be an ordinary directory.')+ entries, total = {}, 0+ for folder, directories, files in os.walk(source, followlinks=False, onerror=walk_error):+ parent = Path(folder)+ relative = parent.relative_to(source)+ target = destination / relative+ target.mkdir(parents=True, exist_ok=True)+ # Do not walk linked directories or follow links out of the project tree.+ for name in sorted(directories + files):+ path = parent / name+ info = path.lstat()+ key = path.relative_to(source).as_posix()+ output = target / name+ if stat.S_ISLNK(info.st_mode):+ link = os.readlink(path)+ output.symlink_to(link, target_is_directory=name in directories)+ entries[key] = {'link': link}+ if name in directories:+ directories.remove(name)+ elif stat.S_ISDIR(info.st_mode):+ output.mkdir(exist_ok=True)+ elif stat.S_ISREG(info.st_mode):+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)+ with os.fdopen(fd, 'rb') as reader:+ before = os.fstat(reader.fileno())+ if not stat.S_ISREG(before.st_mode):+ raise ValueError(f'Project file changed type: {key}')+ sha = hashlib.sha256()+ with output.open('xb') as writer:+ while chunk := reader.read(1024 * 1024):+ writer.write(chunk)+ sha.update(chunk)+ after = os.fstat(reader.fileno())+ if (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns):+ raise ValueError(f'Project is still changing; stop its writes and retry installation: {key}')+ output.chmod(stat.S_IMODE(before.st_mode) & 0o777)+ os.utime(output, ns=(before.st_atime_ns, before.st_mtime_ns))+ # Check what reached the new disk, not only the bytes read from USB.+ with output.open('rb') as written:+ if hashlib.file_digest(written, 'sha256').hexdigest() != sha.hexdigest():+ raise ValueError(f'Project verification failed: {key}')+ entries[key] = {'bytes': before.st_size, 'sha256': sha.hexdigest()}+ total += before.st_size+ else:+ raise ValueError(f'Close the service using this project before installing: {key}')+ # Apply directory metadata after populating them, including read-only directories.+ for folder, directories, _ in os.walk(source, topdown=False, followlinks=False, onerror=walk_error):+ path = Path(folder)+ output = destination / path.relative_to(source)+ info = path.stat()+ output.chmod(stat.S_IMODE(info.st_mode) & 0o777)+ os.utime(output, ns=(info.st_atime_ns, info.st_mtime_ns))+ encoded = json.dumps(entries, sort_keys=True, separators=(',', ':')).encode()+ return {'files': len(entries), 'bytes': total, 'sha256': hashlib.sha256(encoded).hexdigest(), 'entries': entries}+++def size(source):+ if source.is_symlink() or not source.is_dir():+ raise ValueError('The USB Projects folder must be an ordinary directory.')+ total = 0+ for folder, directories, files in os.walk(source, followlinks=False, onerror=walk_error):+ for name in directories + files:+ path = Path(folder) / name+ info = path.lstat()+ if stat.S_ISREG(info.st_mode):+ total += info.st_size+ elif not (stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode)):+ raise ValueError('A trial project contains an active socket or special file. Stop that service before installing.')+ return total+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('action', choices=['size', 'copy'])+ parser.add_argument('source', type=Path)+ parser.add_argument('--destination-fd', type=int)+ args = parser.parse_args()+ if args.action == 'size':+ print(json.dumps({'bytes': size(args.source)}))+ return+ if args.destination_fd is None:+ parser.error('copy requires a destination directory descriptor')+ os.fchdir(args.destination_fd)+ os.close(args.destination_fd)+ print(json.dumps(transfer(args.source, Path('.'))))+++if __name__ == '__main__':+ main()diff --git a/tui/src/app.rs b/tui/src/app.rsindex aa6d2bff7..20f65fcaf 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -664,6 +664,7 @@ pub struct App {pub os_session: bool,/// 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,/// 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`).@@ -871,6 +872,7 @@ impl App {headless: false,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(),wait_channels: HashMap::new(),cli_held: std::collections::VecDeque::new(),last_cli: Instant::now(),@@ -1992,7 +1994,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 self.body() }+ 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()) }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)}@@ -3661,7 +3663,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))+ 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)))}/// tmux's status option: how many status lines (off, on, 2 … 5).@@ -5269,7 +5271,14 @@ impl App {if self.headless { self.shell_asked = true; return }// 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() { self.shell_asked = true; return }+ 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.link(&self.fleet.local_id).is_none() { return }+ self.shell_asked = true;+ crate::input::new_shell_from(self, None, Placement::Auto(None), None, Some("/usr/bin/hn-os welcome".into()));+ } else { self.shell_asked = true; }+ return;+ }// `hn new -s work` (a session besides the desk's): made here, with its shell.if self.start_session.as_ref().map(|s| s.create && self.session_alias.as_deref() != s.name.as_deref()).unwrap_or(false) {if self.link(&self.fleet.local_id).is_none() { return }@@ -5746,6 +5755,7 @@ impl App {}pub fn on_tick(&mut self) {+ crate::os_welcome::tick(self);self.run_start_then();crate::new_harness::welcome_tick(self);self.ask_said();diff --git a/tui/src/bar.rs b/tui/src/bar.rsindex acfe06409..2c4bfbbc3 100644--- a/tui/src/bar.rs+++ b/tui/src/bar.rs@@ -84,6 +84,7 @@ impl App {/// `status off` hides it, and when the terminal is too narrow for it and a window beside it.pub fn bar_side(&self) -> Option<Side> {if self.headless { return None }+ if crate::os_welcome::live(self) { return None }let side = match self.options.status_bar() { "left" => Side::Left, "right" => Side::Right, _ => return None };if self.options.get("status", "", None).as_deref() == Some("off") { return None }if self.size.0 < self.bar_width() + ROOM || self.size.1 < 4 { return None }diff --git a/tui/src/cli.rs b/tui/src/cli.rsindex 5da4914ef..f5fb1124a 100644--- a/tui/src/cli.rs+++ b/tui/src/cli.rs@@ -85,6 +85,7 @@ pub async fn run(args: &[String], explicit_port: Option<u16>, socket: Option<&stlet name = name.map(str::to_string);let cmd = args.first()?.as_str();match cmd {+ "os-action" => Some(crate::ipc::call(args, socket.as_deref(), name.as_deref()).await),"view" | "open-viewer" => Some(crate::viewer::cli(port, &args[1..], socket.as_deref(), name.as_deref()).await),// Every harness on every machine (hn's; `ls` is tmux's list-sessions).// The running client knows each one's state (what it asks, does, did); with none, thediff --git a/tui/src/commands.rs b/tui/src/commands.rsindex 57ae7374e..07c552cf3 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -450,7 +450,7 @@ fn menu_position(app: &App, args: &crate::cmd::Args, target: Option<(usize, u64)pub fn is_command_name(name: &str) -> bool {- COMMANDS.iter().any(|(full, alias, _)| *full == name || *alias == name)+ name == "os-action" || COMMANDS.iter().any(|(full, alias, _)| *full == name || *alias == name)|| matches!(name, "display" | "send" | "neww" | "splitw" | "killp" | "killw" | "selectw" | "selectp" | "lsw" | "lsp" | "ls" | "capturep" | "showw" | "show" | "set" | "bind" | "unbind" | "source" | "run" | "if"| "run-shell" | "if-shell" | "wait-for" | "wait" | "pipe-pane" | "pipep" | "set-hook" | "show-hooks" | "resize-window" | "resizew" | "kill-session" | "send-prefix" | "display-menu" | "menu"| "set-option" | "set-window-option" | "setw" | "bind-key" | "unbind-key" | "source-file" | "kill-server" | "detach-client" | "detach"@@ -1204,7 +1204,7 @@ fn rest(words: &Words) -> String {/// hn's own commands, and the tmux names hn gives its own meaning (checked before tmux's table).pub fn hn_owned(name: &str) -> bool {- COMMANDS.iter().any(|(full, alias, _)| (*full == name || *alias == name) && crate::cmd::find(full).map(|e| e.name != *full).unwrap_or(true))+ name == "os-action" || COMMANDS.iter().any(|(full, alias, _)| (*full == name || *alias == name) && crate::cmd::find(full).map(|e| e.name != *full).unwrap_or(true))}/// A command that names another session (`-t work:2`, `has-session -t work`, a pane's `%12`)@@ -1815,6 +1815,7 @@ fn run_words_in(app: &mut App, words: &[String]) {let client_only = matches!(command, "switch-client" | "detach-client" | "refresh-client" | "suspend-client" | "lock-client" | "display-panes" | "command-prompt" | "confirm-before" | "display-menu" | "display-popup");if app.headless && client_only && !(command == "detach-client" && opt(words, "-s").is_some()) { return app.error("no current client") }match command {+ "os-action" => crate::os_welcome::command(app, &words[1..]),"new-window" => {// tmux's new-window [-abdkPS] [-c dir] [-n name] [-t index] [-F fmt] [command]: a// window with a shell, at -t's index (else the first free one); -a after the targetdiff --git a/tui/src/devices.rs b/tui/src/devices.rsindex e969ad583..88a0340a9 100644--- a/tui/src/devices.rs+++ b/tui/src/devices.rs@@ -69,7 +69,7 @@ impl View {}pub fn of(id: &str) -> Option<View> { View::ALL.into_iter().find(|v| v.id() == id) }pub fn title(self) -> &'static str {- match self { View::Connect => "Connect a machine", View::Phone => "Add your phone", View::Machines => "Machines & devices" }+ match self { View::Connect => "Connect a computer", View::Phone => "Add your phone", View::Machines => "Machines & devices" }}fn placeholder(self) -> &'static str {match self {@@ -454,7 +454,7 @@ fn enter(app: &mut App, view: View) {/// What a view needs read when it opens.fn opened(app: &mut App, view: View) {match view {- View::Connect => load_account(app),+ View::Connect => { load_me(app); load_account(app) }View::Machines => { load_password(app); load_links(app); load_account(app); load_me(app) }View::Phone => {load_me(app);@@ -539,7 +539,10 @@ fn load_me(app: &mut App) {app.devices.phone.email = v.pointer("/user/email").and_then(Value::as_str).map(str::trim).filter(|e| e.contains('@')).map(str::to_string);app.devices.phone.signed_out = false;}- Reply::Http(Err((code, _))) if code == "HTTP_401" => app.devices.phone.signed_out = true,+ Reply::Http(Err((code, _))) if matches!(code.as_str(), "HTTP_401" | "NOT_SIGNED_IN") => {+ app.devices.phone.email = None;+ app.devices.phone.signed_out = true;+ }_ => {}}again(app);@@ -892,6 +895,25 @@ pub fn choose(app: &mut App, view: View, picker: Picker, enter: bool) {let (what, rest) = id.split_once(':').unwrap_or((id.as_str(), ""));let rest = rest.to_string();match (view, what) {+ (View::Connect, "here") if rest == "login" => {+ if app.read_only() { return app.error("This client is read-only.") }+ if app.link(&crate::input::shell_machine(app, None)).is_none() {+ return app.error("This computer is still starting. Try again in a moment.")+ }+ // Use the existing sign-in flow on THIS computer, never whichever+ // remote agent happens to have focus. Leave its outcome readable.+ let executable = std::env::var("HARNESS_CLI").unwrap_or_else(|_| "harness".into());+ let args: Vec<String> = std::env::var("HARNESS_CLI_ARGS").ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();+ let quote = |s: &str| format!("'{}'", s.replace('\'', "'\\''"));+ let command = std::iter::once(executable).chain(args).chain(std::iter::once("login".into())).map(|s| quote(&s)).collect::<Vec<_>>().join(" ");+ let command = format!("{command}; printf '\\nOpen Connect a computer again after signing in.\\nPress Enter to return to Harness. '; read -r harness_login_done");+ app.new_tab();+ app.rename_tab("Sign in");+ let tab = app.tab().id.clone();+ crate::input::new_shell_from(app, None, crate::app::Placement::Fill(tab), None, Some(command));+ return;+ }+ (View::Connect, "here") if rest == "setup" => switch(app, View::Machines),(View::Connect, "m") => { let name = name_of(app, &rest); start_link(app, rest, name) }(_, "m") => sub(app, format!("m:{rest}")),(_, "act") => machine_action(app, &rest),@@ -937,7 +959,7 @@ fn switch(app: &mut App, view: View) {*kind = PickerKind::Devices(view);picker.placeholder = view.placeholder().into();picker.clear_query();- picker.rows.clear();+ picker.set_rows(Vec::new());}again(app);if let Some(p) = picker_mut(app) { p.scroll = 0; p.vset(0, 1) }@@ -1016,6 +1038,11 @@ pub fn fill(app: &App, view: View, picker: &mut Picker) {}fn connect_rows(app: &App) -> Vec<Row> {+ let setup = || Row::new("here:setup", "Set up another computer").group("Get connected").lead(dot("→", theme::TEAL));+ if app.devices.phone.signed_out && !app.daemon_down {+ return vec![Row::new("here:login", "Sign in on this computer").group("Get connected")+ .lead(dot("→", theme::TEAL)).detail(vec![span("Use the same Harness account on both computers.", fg(theme::MUTED))]), setup()];+ }let (mut ready, mut done, mut away) = (Vec::new(), Vec::new(), Vec::new());for m in app.fleet.machines.iter().filter(|m| !m.local) {let (glyph, color, word) = reach(app, m);@@ -1031,9 +1058,10 @@ fn connect_rows(app: &App) -> Vec<Row> {away.push(r);}}- if ready.is_empty() { ready.push(info("none", if app.daemon_down { "Harness is not running on this computer" } else { "Every machine on your account that is online is linked" }, "Not linked yet")) }+ if ready.is_empty() { ready.push(info("none", if app.daemon_down { "Harness is not running on this computer" } else { "No computers ready to connect" }, "Not linked yet")) }ready.extend(done);ready.extend(away);+ ready.push(setup());ready}@@ -1139,7 +1167,14 @@ pub fn preview(app: &App, view: View, id: &str) -> Vec<Line<'static>> {let (what, rest) = id.split_once(':').unwrap_or((id, ""));match what {_ if app.daemon_down && matches!(id, "none" | "m-none") => vec![Line::raw("Harness is not running on this computer."), Line::raw(""), dim("Start it with `harness start`, then come back.").into()],- "none" => vec![Line::raw("Every machine on your account that is online is linked."), Line::raw(""), dim("To add another: Machines & devices… › Add a machine.").into()],+ "none" => vec![Line::raw("No computers are ready to connect."), Line::raw(""), dim("Open Harness on the other computer and sign in to the same account.").into()],+ "here" if rest == "login" => vec![Line::raw("Sign in to see your other computers."), Line::raw(""),+ dim("Use the same Harness account on both. Your local agents work without signing in.").into(),+ Line::raw(""), dim("After signing in, open Connect a computer again.").into(),+ Line::raw(""), dim("Enter opens the normal Harness sign-in flow in a local terminal.").into()],+ "here" => vec![Line::raw("Set up Harness on your other computer."), Line::raw(""),+ dim("The setup guide covers sign-in, the remote password and servers.").into(),+ Line::raw(""), dim("Enter opens Machines & devices.").into()],"m" => {let mut out = machine_lines(app, rest);if view == View::Connect {@@ -1192,7 +1227,7 @@ pub fn preview(app: &App, view: View, id: &str) -> Vec<Line<'static>> {"add" => {let (text, copies): (&str, String) = match rest {"download" => ("Download Harness on your other computer and sign in with the same account.", DOWNLOAD_URL.into()),- "connect" => ("On the other computer: Machines → Set password. Back here, Connect a machine and enter that password.", String::new()),+ "connect" => ("On the other computer: Machines → Set password. Back here, Connect a computer and enter that password.", String::new()),"install" => ("Run these on your server over SSH:", INSTALL.into()),"login" => ("Open the printed sign-in link in a browser on any device.", LOGIN.into()),"start" => ("Start Harness and set a remote password.", START.into()),@@ -1200,7 +1235,7 @@ pub fn preview(app: &App, view: View, id: &str) -> Vec<Line<'static>> {};let mut out = vec![Line::raw(text.to_string()), Line::raw("")];for l in copies.lines() { out.push(Line::from(vec![Span::styled(l.to_string(), fg(theme::TEAL))])) }- out.extend(enter_does(if copies.is_empty() { "opens Connect a machine".to_string() } else { "copies it — to the clipboard of the computer you sit at".to_string() }));+ out.extend(enter_does(if copies.is_empty() { "opens Connect a computer".to_string() } else { "copies it — to the clipboard of the computer you sit at".to_string() }));out}"ph" => {@@ -1548,10 +1583,31 @@ mod tests {crate::input::run(&mut app, "connect-machine");let Some(Modal::Picker { picker, .. }) = &app.modal else { panic!() };let usable: Vec<&str> = picker.rows.iter().filter(|r| !r.disabled).map(|r| r.id.as_str()).collect();- assert_eq!(usable, vec![format!("m:{REMOTE}").as_str()]);+ assert_eq!(usable, vec![format!("m:{REMOTE}").as_str(), "here:setup"]);assert!(picker.rows.iter().any(|r| r.id == format!("m:{OFF}") && r.disabled), "an offline one is shown, not chosen");}+ #[test]+ fn signed_out_connect_explains_the_next_step_and_setup_stays_reachable() {+ for code in ["HTTP_401", "NOT_SIGNED_IN"] {+ let mut app = app((150, 42));+ app.fleet.machines.retain(|m| m.local);+ app.devices.runner = Some(Box::new(move |req| match req {+ Req::Http { path, .. } if path == "/api/auth/me" => Some(Reply::Http(Err((code.into(), "Sign in".into())))),+ _ => world(req),+ }));+ open(&mut app, View::Connect);+ assert_eq!(ids(&app), vec!["here:login", "here:setup"]);+ go_to(&mut app, "here:login");+ let (text, _) = screen(&mut app, 150, 42);+ assert!(text.contains("Sign in on this computer") && text.contains("local agents work without"), "{text}");+ assert!(!text.contains("Every machine on your account"));+ go_to(&mut app, "here:setup");+ press(&mut app, KeyCode::Enter);+ assert!(matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Devices(View::Machines), .. })));+ }+ }+#[test]fn connecting_asks_the_password_hidden_then_yes_then_shows_each_stage() {let mut app = app((150, 42));diff --git a/tui/src/input.rs b/tui/src/input.rsindex 5ef9a9855..dc5e8b9a3 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -57,6 +57,7 @@ fn typing(app: &App) -> bool {}fn on_key(app: &mut App, key: KeyEvent) {+ if crate::os_welcome::key(app, key) { return }let chord = keys::of(&key);app.key_name = Some(keys::name(&chord));// A message goes on the next key, as tmux's does.@@ -279,6 +280,7 @@ pub(crate) fn paste_form(app: &mut App, text: &str) -> bool {}fn on_mouse(app: &mut App, mouse: MouseEvent) {+ if crate::os_welcome::mouse(app, mouse) { return }// tmux asks the terminal for bare motion only when a pane here wants it (or a menu opened by// the mouse): the rest of the motion hn is sent never happened, as far as tmux is concerned.if matches!(mouse.kind, MouseEventKind::Moved) && !app.wants_motion() { return }@@ -541,7 +543,7 @@ fn os_home_command(app: &App, key: KeyEvent) -> Option<Option<&'static str>> {KeyCode::Enter if app.os_live => Some(Some("sudo /usr/bin/harness install")),KeyCode::Char('i' | 'I') if app.os_live => Some(Some("sudo /usr/bin/harness install")),KeyCode::Enter => Some(Some("/usr/bin/hn-os try")),- KeyCode::Char('t' | 'T') if app.os_live => Some(Some("/usr/bin/hn-os try")),+ KeyCode::Char('t' | 'T') if app.os_live => Some(Some("/usr/bin/hn-os welcome")),KeyCode::Char('w' | 'W') => Some(Some("/usr/bin/hn-os wifi")),KeyCode::Char('t' | 'T') => Some(None),_ => None,@@ -1285,6 +1287,7 @@ fn shell_placed(app: &mut App, machine: String, placement: Placement, reply: Resp.queued.extend(typed);p.start_command = reply.pointer("/agent/startCommand").and_then(serde_json::Value::as_str).map(str::to_string);}+ crate::os_welcome::shell_created(app, pane);// A new session's first pane may belong to a session not currently in front.let (back, before) = (app.session_id, app.swap_back);if session != back { app.swap_back = Some(back); app.swap_session(session); }@@ -3289,7 +3292,7 @@ mod tests {for code in [KeyCode::Enter, KeyCode::Char('i'), KeyCode::Char('I')] {assert_eq!(os_home_command(&app, key(code)), Some(Some("sudo /usr/bin/harness install")));}- assert_eq!(os_home_command(&app, key(KeyCode::Char('T'))), Some(Some("/usr/bin/hn-os try")));+ assert_eq!(os_home_command(&app, key(KeyCode::Char('T'))), Some(Some("/usr/bin/hn-os welcome")));for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT, KeyModifiers::SUPER] {assert_eq!(os_home_command(&app, KeyEvent::new(KeyCode::Enter, modifiers)), None);}diff --git a/tui/src/main.rs b/tui/src/main.rsindex 6c36bcdbd..d60f99ec1 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -39,6 +39,7 @@ mod modal;mod new_harness;mod mouse;mod options;+mod os_welcome;mod paste;mod pane;mod pane_frame;diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex ad762c976..6d85c93a2 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -205,7 +205,7 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("machines", "Machines", "⌥M", "", "Machines"),("store", "Harness store", "⌥S", "", "Machines"),// ── machines & devices ──- ("connect-machine", "Connect a machine…", "", "a machine not linked yet, with its remote password", "Machines"),+ ("connect-machine", "Connect a computer…", "", "a computer not linked yet, with its remote password", "Machines"),("add-phone", "Add phone…", "", "a QR code your phone scans to sign in and pair", "Machines"),("devices", "Machines & devices…", "", "this computer's password, your machines, links, add a machine", "Machines"),// (hn itself: how it looks, its keys, and closing it.)diff --git a/tui/src/mouse.rs b/tui/src/mouse.rsindex 1fde805d6..364c261ac 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) as i32 };+ 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.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.rsnew file mode 100644index 000000000..00a1b928e--- /dev/null+++ b/tui/src/os_welcome.rs@@ -0,0 +1,376 @@+//! USB onboarding belongs to the OS launcher. Ordinary hn never enters this module's 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}};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Action { Install, Wifi, New, Connect, Terminal, Dismiss }++#[derive(Default)]+pub struct State {+ pub guide_pane: Option<u64>,+ pub dock_focus: Option<Action>,+ pub hits: Vec<(Rect, Action)>,+ pub network: Option<bool>,+ welcome_panes: Vec<u64>,+ install_pane: Option<u64>,+ wifi_pane: Option<u64>,+ install_tab: Option<String>,+ wifi_tab: Option<String>,+}++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 }+ 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 this_computer(app: &App, machine: &str) -> bool {+ machine == app.fleet.local_id || crate::local::is_local(machine)+}++/// Record the originating request once. Terminal discovery can later replace+/// start_command with the underlying login shell's command, so it is not an ID.+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) => {+ if !app.os_welcome.welcome_panes.contains(&id) { app.os_welcome.welcome_panes.push(id); }+ }+ 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),+ _ => {}+ }+}++/// Always create system forms on this computer, even while a remote pane has focus.+fn local_dialog(app: &mut App, name: &str, command: &str, install: bool) {+ let held = if install { &app.os_welcome.install_tab } else { &app.os_welcome.wifi_tab };+ let pane = if install { app.os_welcome.install_pane } else { app.os_welcome.wifi_pane };+ let existing = app.tabs.iter().position(|tab| (held.as_ref() == Some(&tab.id) && app.shell_inputs.contains_key(&tab.id))+ || pane.is_some_and(|id| tab.panes().contains(&id) && app.panes.get(&id).is_some_and(|p| this_computer(app, &p.machine_id))));+ if let Some(index) = existing {+ app.modal = None;+ if let Some(id) = pane.filter(|id| app.tabs[index].panes().contains(id)) { app.focus_pane(index, id); }+ else { app.select_tab(index); }+ return;+ }+ if app.link(&crate::input::shell_machine(app, None)).is_none() { return app.error("This computer is still starting. Try again in a moment.") }+ app.new_tab();+ app.rename_tab(name);+ let tab = app.tab().id.clone();+ if install { app.os_welcome.install_tab = Some(tab.clone()); } else { app.os_welcome.wifi_tab = Some(tab.clone()); }+ crate::input::new_shell_from(app, None, Placement::Fill(tab), None, Some(command.into()));+}++pub fn act(app: &mut App, action: Action) {+ 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.") }+ app.os_welcome.dock_focus = None;+ match action {+ Action::Install if live(app) => local_dialog(app, "Install", "sudo /usr/bin/harness install", true),+ Action::Install => app.error("Installation is available from the Harness USB."),+ Action::Wifi => local_dialog(app, "Wi-Fi", "/usr/bin/hn-os wifi", false),+ Action::New => crate::new_harness::open(app, None, None),+ Action::Connect => crate::devices::open(app, crate::devices::View::Connect),+ Action::Terminal => crate::input::run(app, "terminal"),+ Action::Dismiss => { app.os_welcome.guide_pane = None; app.fit_panes(); }+ }+}++/// Private OS integration: absent from ordinary hn's command and welcome menus.+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.");+ };+ // 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.") };+ app.os_welcome.guide_pane = Some(pane);+ app.fit_panes();+ return;+ }+ let action = match args.first().map(String::as_str) {+ Some("install") => Action::Install, Some("wifi") => Action::Wifi,+ Some("new") => Action::New, Some("connect") => Action::Connect,+ Some("terminal") => Action::Terminal, Some("dismiss") => Action::Dismiss,+ _ => return app.error("Unknown OS action."),+ };+ 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); }+ }+}++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);+ }+}++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+}++pub fn key(app: &mut App, key: KeyEvent) -> bool {+ if !live(app) || app.modal.is_some() { return false }+ if key.code == KeyCode::F(10) && key.modifiers.is_empty() {+ app.os_welcome.dock_focus = Some(Action::Install);+ return true;+ }+ 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::Enter | KeyCode::Char(' ') => act(app, action),+ _ => { app.os_welcome.dock_focus = None; return false }+ }+ return true;+ }+ false+}++#[cfg(test)]+mod tests {+ use super::*;+ use crossterm::event::KeyModifiers;++ fn fixture(width: u16, height: u16) -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (width, height));+ app.handed_over = true;+ app.os_session = true;+ app.os_live = true;+ app+ }++ fn contents(buf: &Buffer) -> String {+ (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));+ }+ }+ }++ #[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");+ }++ #[tokio::test]+ async fn keyboard_dock_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))));+ }++ #[tokio::test]+ async fn private_actions_cannot_install_on_ordinary_or_installed_hn() {+ for (os, live) in [(false, false), (false, true), (true, false)] {+ let mut app = fixture(100, 30);+ app.os_session = os;+ app.os_live = live;+ let tabs = app.tabs.len();+ command(&mut app, &["install".into()]);+ assert!(app.starting_shell.is_none());+ assert_eq!(app.tabs.len(), tabs);+ }+ }++ #[tokio::test]+ async fn install_reuses_its_local_form_even_when_a_remote_pane_is_focused() {+ let mut app = fixture(120, 40);+ app.fleet.local_id = "local-daemon".into();+ app.open_agent("local-daemon", "installer", Placement::Auto(None));+ let installer = app.focused().unwrap();+ app.panes.get_mut(&installer).unwrap().start_command = Some("sudo /usr/bin/harness install".into());+ shell_created(&mut app, installer);+ // Discovery reports the original login shell after it has exec'd the+ // form. Its new title/command must not cause a second installer.+ app.panes.get_mut(&installer).unwrap().start_command = Some("/bin/bash -l".into());+ let install_tab = app.tab().id.clone();+ app.open_agent("remote", "same-tab-work", Placement::Auto(None));+ app.new_tab();+ app.open_agent("remote", "work", Placement::Auto(None));+ act(&mut app, Action::Install);+ assert_eq!(app.tab().id, install_tab);+ assert_eq!(app.focused(), Some(installer));+ assert_eq!(app.tabs.len(), 2, "repeated requests must not create another installer");+ assert!(app.starting_shell.is_none());+ }++ #[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);+ 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");+ 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"));+ }++ #[tokio::test]+ async fn usb_ready_cannot_resize_an_unrelated_or_remote_pane() {+ let mut app = fixture(120, 40);+ app.open_agent("remote", "agent", Placement::Auto(None));+ let pane = app.focused().unwrap();+ command(&mut app, &["ready".into(), format!("%{}", pane - 1)]);+ assert!(app.os_welcome.guide_pane.is_none());+ let local = crate::local::MACHINE.to_string();+ let p = app.panes.get_mut(&pane).unwrap();+ p.machine_id = local;+ p.start_command = Some("/usr/bin/hn-os welcome".into());+ shell_created(&mut app, pane);+ command(&mut app, &["ready".into(), format!("%{}", pane - 1)]);+ assert_eq!(app.os_welcome.guide_pane, Some(pane));+ assert!(crate::commands::is_command_name("os-action"));+ }++ #[tokio::test]+ async fn readiness_maps_the_backend_pane_instead_of_assuming_the_same_number() {+ let mut app = fixture(120, 40);+ app.fleet.local_id = "local-daemon".into();+ let row = serde_json::json!({"id": "welcome", "engine": "terminal", "tmuxPane": "%997"});+ app.fleet.agents.insert(("local-daemon".into(), "welcome".into()), crate::fleet::agent_from("local-daemon", &row, None));+ app.open_agent("local-daemon", "welcome", Placement::Auto(None));+ let pane = app.focused().unwrap();+ app.panes.get_mut(&pane).unwrap().start_command = Some("/usr/bin/hn-os welcome".into());+ shell_created(&mut app, pane);+ app.panes.get_mut(&pane).unwrap().start_command = Some("/bin/bash -l".into());+ assert_ne!(crate::pane::tag(pane), "%997");+ app.new_tab();+ app.open_agent("remote", "other-work", Placement::Auto(None));+ let current = app.focused();+ command(&mut app, &["ready".into(), "%997".into()]);+ assert_eq!(app.os_welcome.guide_pane, Some(pane));+ assert_eq!(app.focused(), current, "readiness must not change the current work");+ }+}diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 85c6b8f5c..6a517cdc4 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 - lines }, area.width, lines);+ 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 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,6 +193,7 @@ 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();@@ -254,6 +255,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) {let hidden = app.status_lines() == 0;let speaking = matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Confirm { .. })) || app.toast.as_ref().map(|(_, _, at)| at.elapsed() < Duration::from_millis(app.toast_ms())).unwrap_or(false);if !hidden || speaking { if let Some(pos) = status_line(buf, app, status) { cursor = Some(pos) } }+ crate::os_welcome::draw_dock(buf, app);// A menu is tmux's overlay: over the status line too, where it is kept on the screen.if let Some(Modal::Menu(m)) = &app.modal { menu(buf, app, m) }if let Some(Modal::NewHarness(form)) = &mut app.modal { cursor = crate::new_harness::draw(buf, body, form); }@@ -592,16 +594,15 @@ fn os_welcome(buf: &mut Buffer, app: &App, area: Rect) {} else { lines.push(Line::styled("harness", bold(theme::accent()))) }lines.push(Line::raw(""));let centered = lines.len();- let actions = if app.os_live { vec![("Enter", "Install Harness"), ("T", "Try without installing")] }- else { vec![("Enter", "Start OpenCode"), ("T", "New terminal"), ("W", "Connect to Wi-Fi")] };+ let actions = if app.os_live { vec![("Enter", "Install Harness"), ("t", "Try without installing")] }+ else { vec![("Enter", "Start OpenCode"), ("t", "New terminal"), ("w", "Connect to Wi-Fi")] };for (key, action) in actions {lines.push(Line::from(vec![Span::styled(format!("{key:7}"), bold(theme::accent())), Span::styled(action, bold(theme::TEXT))]));lines.push(Line::raw(""));}lines.push(Line::raw(""));- let prefix = crate::keys::name(&app.keymap.prefix);- lines.push(Line::styled(format!("{prefix} T terminal · {prefix} W Wi-Fi · Super+B browser"), fg(theme::MUTED)));- if app.os_live { lines.push(Line::styled(format!("Inside a session: {prefix} I install"), fg(theme::MUTED))) }+ lines.push(Line::styled("Super+t terminal · Super+w Wi-Fi · Super+b browser", fg(theme::MUTED)));+ if app.os_live { lines.push(Line::styled("Super+i install", fg(theme::MUTED))) }let width = area.width.saturating_sub(4).min(58);let left = area.x + area.width.saturating_sub(width) / 2;let top = area.y + area.height.saturating_sub(lines.len() as u16) / 2;@@ -631,13 +632,13 @@ mod os_welcome_tests {empty_window(&mut buf, &mut app, area);let text = (0..height).map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n");if !os {- for action in ["Install Harness", "Try without installing", "Wi-Fi", "Super+B"] {+ for action in ["Install Harness", "Try without installing", "Wi-Fi", "Super+b"] {assert!(!text.contains(action), "ordinary hn must not offer {action}: {text}");}assert!(text.contains("Task"), "{text}");} else if live {assert!(text.contains("Enter Install Harness"), "{text}");- assert!(text.contains("T Try without installing"), "{text}");+ assert!(text.contains("t Try without installing"), "{text}");assert!(!text.contains("Nothing running"), "{text}");} else {assert!(text.contains("Start OpenCode"), "{text}");diff --git a/tui/tests/native-terminal.py b/tui/tests/native-terminal.pyindex 407df8b63..166c2778d 100644--- a/tui/tests/native-terminal.py+++ b/tui/tests/native-terminal.py@@ -441,7 +441,14 @@ try:both('split-window', '-d', '-t', 'work:4', 'sleep 30')first_id = same('list-panes', '-t', 'work:4', '-F', '#{pane_id}').splitlines()[0]both('select-window', '-t', 'work:0')- both('respawn-window', '-k', '-t', 'work:4', 'printf "WHOLE_WINDOW\\n"; exit 9')+ # Check whole-window replacement after the new shell is ready. Immediate+ # exit here races the reference tmux's old-child signal reaping; rapid exits+ # have their own paired coverage below.+ both('respawn-window', '-k', '-t', 'work:4', 'printf "WHOLE_WINDOW\\n"; read -r status; exit 9')+ wait(lambda: same('list-panes', '-t', 'work:4', '-F', '#{pane_id}:#{pane_dead}') == first_id + ':0'+ and all('WHOLE_WINDOW' in cli(kind, 'capture-pane', '-p', '-t', 'work:4').stdout+ for kind in ('hn', 'tmux')), 'whole-window replacement ready')+ both('send-keys', '-t', 'work:4', '9', 'Enter')wait(lambda: same('list-panes', '-t', 'work:4', '-F', '#{pane_id}:#{pane_dead}:#{pane_dead_status}') == first_id + ':1:9', 'whole-window respawn keeps only the first pane')assert same('display', '-p', '-t', 'work', '#{window_index}') == '4'assert 'WHOLE_WINDOW' in same('display', '-p', '-t', 'work:4', '#{pane_start_command}')