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
Shrink the Harness USB image and fix first-use installation (#707)
Dee91535961dd82
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex b4ae0baf0..154827dcd 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -5,9 +5,10 @@ boot changes. Reflashing is a release/install test, not the intended way to tryevery interface fix. Keep the development tools on the build/test host; theinstalled OS keeps the same minimal interface.-This plan was recorded on October 3, 2026. Preview 6 and its small bootstrap bundle-and update channel are published. Native upgrades from previews 4 and 5 passed; remote-launcher-argument tests passed but remote display/SSH interaction is still unverified.+This plan was recorded on October 3, 2026. Preview 7 and its small bootstrap bundle+and update channel are published. Its native upgrade from preview 6 passed; earlier+preview 6 coverage includes upgrades from previews 4 and 5. Remote-launcher argument+tests passed but remote display/SSH interaction is still unverified.## Next release priorities@@ -140,6 +141,32 @@ through Actions with the existing image's `image_run_id` and independently trustno release defaults. Adopting a candidate requires a production image build andthe normal plain/encrypted installation, agent trial and recovery checks.+The [October 4 preview 7 comparison](https://github.com/autonomous-ai/openharness/actions/runs/37177303376)+verified 87,985 paths and 1,035 hardlink groups through all nine extractions. All+eight native installations passed. Level 19 saved 80.14 MiB (5.30%) versus the+same-tool level-6 payload. Full BIOS install medians were 31.937/32.684 seconds;+the encrypted pair was 56.353/57.787 seconds, including final sync and unmount.+Preview 8 adopts level 19 for the USB only; installed Btrfs compression is unchanged.++Both encrypted trials fell below 128 MiB available RAM (69.20/94.07 MiB minimum),+with 105.34/91.69 MiB peak swap. That baseline pressure is not a regression caused+by the new compression in these samples, nor proof of a memory improvement.+Per-command timing was not captured in that assessment. A later full preview 8+journey ([37181312268](https://github.com/autonomous-ai/openharness/actions/runs/37181312268))+identified the failure directly: during encryption after an agent trial, the+kernel killed `cryptsetup luksFormat` at 485,232 KiB anonymous RSS. The 1 GiB guest's+RAM-backed swap was almost full. The plain and separate hardware installations passed.++The installer now limits PBKDF memory to half of available RAM, leaves at least+128 MiB for the live session, and retains cryptsetup's 1 GiB ceiling. It refuses+to erase the disk if the resulting budget is below 64 MiB. Cipher, key size,+Argon2id and the normal time/iteration benchmark remain intact; lower-memory+machines can get a lower memory cost. Existing encrypted disks are never changed.+This follows cryptsetup's supported [memory budgeting](https://gitlab.com/cryptsetup/cryptsetup/-/blob/main/man/common_options.adoc)+and accounts for its [swap-dependent free-memory check](https://gitlab.com/cryptsetup/cryptsetup/-/blob/main/lib/utils_pbkdf.c).+The native journey records actual keyslot costs and checks unlock/recovery.+Shared-host VMs do not establish physical 1 GiB hardware reliability.+## The feedback loop| Work being tested | Best environment | What it proves |diff --git a/os/INSTALL.md b/os/INSTALL.mdindex 85be9a733..5e5a0eb3f 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.7**, using a Mac to prepare the USB.+These instructions are for **0.1.0-preview.8**, 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 7 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.7),+From the [preview 8 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.8),download both files into the same folder:-- `harness-0.1.0-preview.7-x86_64.iso`-- `harness-0.1.0-preview.7-x86_64.iso.sha256`+- `harness-0.1.0-preview.8-x86_64.iso`+- `harness-0.1.0-preview.8-x86_64.iso.sha256`If they are in Downloads, open Terminal and run:```shcd ~/Downloads-shasum -a 256 -c harness-0.1.0-preview.7-x86_64.iso.sha256+shasum -a 256 -c harness-0.1.0-preview.8-x86_64.iso.sha256```-The result must say `harness-0.1.0-preview.7-x86_64.iso: OK`.+The result must say `harness-0.1.0-preview.8-x86_64.iso: OK`.If it does not, download the files again before flashing.## 3. Flash the USB@@ -183,8 +183,11 @@ They retain a recovery checkpoint and rebuild the boot image. When the screenoffers **Restart now**, save your work and press Enter when ready. Downloads donot restart the computer, and routine updates do not require another USB flash.-Preview 4 needs the small bootstrap bundle from the new preview release once.-Verify and extract that bundle, open a terminal in its folder, and run:+Preview 8 reduces the USB download size; it does not require an update or reflash+on an installed preview 7 computer. The installed-system feed remains on preview 7.++Preview 4 needs the 7.2 MB [preview 7 bootstrap bundle](https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.7/harness-update-0.1.0-preview.7-47872670a-x86_64.zip)+once. Verify and extract that bundle, open a terminal in its folder, and run:```shsha256sum -c SHA256SUMSdiff --git a/os/README.md b/os/README.mdindex 91a5fc926..d5f6d41de 100644--- a/os/README.md+++ b/os/README.md@@ -11,7 +11,7 @@ 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+**Preview 8:** the USB opens a short network stepor goes straight into bundled OpenCode when already connected. **Install withoutconnecting** opens the same native installer offline. The agent works beside**New Harness** and **Connect a computer** starter panels; a persistent install@@ -19,19 +19,25 @@ dock keeps the USB's temporary state clear. Saved `~/Projects` files are copiedand verified during installation. The full TUI reference and OS guide are bundledfor 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 OpenCode-with its upstream default settings. The installer has four fields and one Install-action; encrypted boot shows the Harness wordmark and a masked password prompt.+The installer has four fields and one Install action; encrypted boot shows the+Harness wordmark and a masked password prompt.Both the live and installed system use `me@harness`.`Super+u` opens Updates. Frequent hn/CLI releases download in the background;you choose when to reconnect the screen. Running agents and terminals stay alive.-[Download preview 6](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.6)+[Download preview 8](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.8)· [Mac → USB → ThinkPad installation guide](INSTALL.md)· [Standalone HTML/CSS landing page](../website/public/os/README.md)· [Development feedback loop and Mac support targets](DEVELOPMENT.md)+Preview 8 uses stronger USB payload compression and fixes a startup race: opening+a terminal immediately can no longer send the USB welcome into that new window.+Encrypted installation also budgets key derivation against available RAM,+without treating RAM-backed swap as extra capacity after the agent trial.+These changes concern the live USB; existing installations do not need updating or+reflashing for them. The installed system update feed remains independent from+ISO packaging.+Each published image includes its matching installation guide and exact validationevidence. Preview 6 passed BIOS/plain and UEFI/encrypted USB installation, boot,update retry and recovery at 1 GiB and 4 GiB RAM. First-use model conversations,diff --git a/os/build.sh b/os/build.shindex 8daa4b78b..a35e89fc2 100644--- a/os/build.sh+++ b/os/build.sh@@ -70,7 +70,8 @@ iso_publisher="OpenHarness"iso_application="Harness: boot into hn"iso_version="$VERSION"airootfs_image_type="squashfs"-airootfs_image_tool_options=("-comp" "zstd" "-Xcompression-level" "6" "-b" "1M")+# Match the measured compression profile and bound builder CPU/cache use.+airootfs_image_tool_options=("-comp" "zstd" "-Xcompression-level" "19" "-b" "1M" "-processors" "2" "-mem" "1G")file_permissions=(["/root"]="0:0:750")diff --git a/os/installer.py b/os/installer.pyindex e08e62745..fb416c7e1 100644--- a/os/installer.py+++ b/os/installer.py@@ -27,6 +27,26 @@ INSTALL_LOG = Path('/var/log/harness-install.log')LAST_LOG = None+def encryption_memory(meminfo=Path('/proc/meminfo')):+ """Budget Argon2 against RAM, not zram advertised as additional swap."""+ try:+ values = {name: int(value) for name, value in re.findall(+ r'^(MemTotal|MemAvailable):\s+(\d+) kB$', meminfo.read_text(), re.M)}+ total, available = values['MemTotal'], values['MemAvailable']+ if not 0 < available <= total:+ raise ValueError('Invalid memory information')+ except (OSError, KeyError, ValueError) as error:+ raise ValueError('Cannot check available memory for encryption. No disk has been erased.') from error+ # Cryptsetup normally uses at most half of physical RAM, up to 1 GiB.+ # Its extra free-memory limit applies only without swap. Zram is RAM too:+ # leave half of available RAM and at least 128 MiB for the live session.+ budget = min(1024 * 1024, total // 2, available // 2, available - 128 * 1024)+ budget = budget // 1024 * 1024+ if budget < 64 * 1024:+ raise ValueError('Not enough free memory for encryption. Close other harnesses and browser windows, then try again. No disk has been erased.')+ return budget++@contextmanagerdef command_log(path):"""Keep command output off the form. Never record stdin (which may be a password)."""@@ -224,6 +244,7 @@ def install(config, source, target, progress=None):kernel = preflight(config, source)trial = trial_source(config)selected_disk(config)+ pbkdf_memory = encryption_memory() if config['encrypt'] else Nonestarted = time.monotonic()disk = config['disk']_, boot, root_partition = partitions(disk)@@ -242,8 +263,10 @@ def install(config, source, target, progress=None):root_device = root_partitionluks_uuid = Noneif config['encrypt']:+ report('Setting up encryption…')secret = config['password'].encode()- run('cryptsetup', 'luksFormat', '--type', 'luks2', '--batch-mode', '--key-file=-', root_partition, input=secret)+ run('cryptsetup', 'luksFormat', '--type', 'luks2', '--batch-mode',+ '--pbkdf-memory', pbkdf_memory, '--key-file=-', root_partition, input=secret)run('cryptsetup', 'open', '--key-file=-', root_partition, mapper, input=secret)opened = Trueroot_device = f'/dev/mapper/{mapper}'@@ -365,6 +388,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 pbkdf_memory is not None:+ receipt['pbkdf_memory_limit_kib'] = pbkdf_memoryif trial_receipt is not None:receipt['trial_projects'] = trial_receiptwrite(target, '/var/lib/harness-os/install.json', json.dumps(receipt, indent=2) + '\n')diff --git a/os/lock.json b/os/lock.jsonindex 2bf264579..eecc5532b 100644--- a/os/lock.json+++ b/os/lock.json@@ -1,8 +1,9 @@{- "version": "0.1.0-preview.7",+ "version": "0.1.0-preview.8","arch_snapshot": "2026/10/01","architecture": "x86_64","upgrades_from": [+ {"version": "0.1.0-preview.7", "arch_snapshot": "2026/10/01"},{"version": "0.1.0-preview.6", "arch_snapshot": "2026/10/01"},{"version": "0.1.0-preview.5", "arch_snapshot": "2026/10/01"},{"version": "0.1.0-preview.4", "arch_snapshot": "2026/10/01"}diff --git a/os/tests/payload_compression.py b/os/tests/payload_compression.pyindex 1954f48c7..e8ad95071 100644--- a/os/tests/payload_compression.py+++ b/os/tests/payload_compression.py@@ -227,7 +227,7 @@ def main():source_date_epoch=os.environ.get('SOURCE_DATE_EPOCH')),limits=['Host extraction is not a complete installation or boot test.','The 64 MiB SquashFS cache does not constrain total host memory.',- 'Published level 6 uses a different toolchain; use rebuilt level 6 as control.',+ 'Published payload may use a different toolchain; use rebuilt level 6 as control.','No candidate is promoted by this assessment.'])try:result['test_source_commit'] = subprocess.check_output(diff --git a/os/tests/test_installer.py b/os/tests/test_installer.pyindex 58a01e389..2c60c687c 100644--- a/os/tests/test_installer.py+++ b/os/tests/test_installer.py@@ -115,6 +115,90 @@ class LivePayload(unittest.TestCase):self.assertEqual(installer.live_payload(explicit), explicit)+class EncryptionMemory(unittest.TestCase):+ def budget(self, total_mib, available_mib, swap_mib=0):+ with tempfile.TemporaryDirectory() as temp:+ info = Path(temp) / 'meminfo'+ info.write_text(f'MemTotal: {total_mib * 1024} kB\nMemAvailable: {available_mib * 1024} kB\nSwapFree: {swap_mib * 1024} kB\n')+ return installer.encryption_memory(info)++ def test_ram_backed_swap_does_not_increase_encryption_budget(self):+ self.assertEqual(self.budget(960, 400, swap_mib=480), 200 * 1024)+ self.assertEqual(self.budget(960, 400, swap_mib=4096), 200 * 1024)+ self.assertEqual(self.budget(960, 400), 200 * 1024)++ def test_budget_preserves_headroom_and_the_normal_one_gib_ceiling(self):+ self.assertEqual(self.budget(960, 224), 96 * 1024)+ self.assertEqual(self.budget(960, 192), 64 * 1024)+ self.assertEqual(self.budget(16384, 12000), 1024 * 1024)+ with self.assertRaisesRegex(ValueError, 'Close other harnesses'):+ self.budget(960, 191)++ def test_missing_or_invalid_memory_is_not_treated_as_available(self):+ with tempfile.TemporaryDirectory() as temp:+ info = Path(temp) / 'meminfo'+ for content in [None, '', 'MemTotal: 1000 kB\n',+ 'MemTotal: 1000 kB\nMemAvailable: 1001 kB\n']:+ if content is not None:+ info.write_text(content)+ with self.assertRaisesRegex(ValueError, 'No disk has been erased'):+ installer.encryption_memory(info)++ def test_insufficient_memory_stops_before_creating_or_erasing_the_target(self):+ config = dict(username='me', hostname='harness', password='test-password',+ encrypt=True, disk='/dev/vda', confirm_erase='/dev/vda')+ with tempfile.TemporaryDirectory() as temp:+ source, target = Path(temp) / 'payload', Path(temp) / 'target'+ source.touch()+ with patch.object(installer, 'selected_disk'), \+ patch.object(installer, 'preflight'), \+ patch.object(installer, 'trial_source'), \+ patch.object(installer, 'encryption_memory', side_effect=ValueError('Not enough free memory')), \+ patch.object(installer, 'run') as commands:+ with self.assertRaisesRegex(ValueError, 'Not enough free memory'):+ installer.install(config, source, target)+ commands.assert_not_called()+ self.assertFalse(target.exists())++ def test_format_uses_the_budget_without_overriding_time_or_algorithm(self):+ config = dict(username='me', hostname='harness', password='test-password',+ encrypt=True, disk='/dev/vda', confirm_erase='/dev/vda')+ def stop_at_open(*args, **kwargs):+ if args[:2] == ('cryptsetup', 'open'):+ raise OSError('stop before mapping a real disk')+ with tempfile.TemporaryDirectory() as temp:+ source = Path(temp) / 'payload'+ source.touch()+ with patch.object(installer, 'selected_disk'), \+ patch.object(installer, 'preflight'), \+ patch.object(installer, 'trial_source', return_value=None), \+ patch.object(installer, 'encryption_memory', return_value=192 * 1024), \+ patch.object(installer, 'run', side_effect=stop_at_open) as commands:+ with self.assertRaisesRegex(OSError, 'stop before mapping'):+ installer.install(config, source, Path(temp) / 'target')+ call = next(c for c in commands.call_args_list if c.args[:2] == ('cryptsetup', 'luksFormat'))+ self.assertEqual(call.args[call.args.index('--pbkdf-memory') + 1], 192 * 1024)+ self.assertEqual(call.args[call.args.index('--type') + 1], 'luks2')+ self.assertEqual(call.kwargs['input'], b'test-password')+ for option in ['--iter-time', '--pbkdf-force-iterations', '--pbkdf', '--cipher', '--key-size']:+ self.assertNotIn(option, call.args)++ def test_plain_install_does_not_require_an_encryption_budget(self):+ config = dict(username='me', hostname='harness', password='test-password',+ encrypt=False, disk='/dev/vda', confirm_erase='/dev/vda')+ with tempfile.TemporaryDirectory() as temp:+ source = Path(temp) / 'payload'+ source.touch()+ with patch.object(installer, 'selected_disk'), \+ patch.object(installer, 'preflight'), \+ patch.object(installer, 'trial_source', return_value=None), \+ patch.object(installer, 'encryption_memory') as budget, \+ patch.object(installer, 'run', side_effect=OSError('stop before erasing')):+ with self.assertRaisesRegex(OSError, 'stop before erasing'):+ installer.install(config, source, Path(temp) / 'target')+ budget.assert_not_called()++class Screen:"""Capture drawn text and supply keys; never expose a real disk or terminal."""def __init__(self):diff --git a/os/tests/vm.py b/os/tests/vm.pyindex 824bf1e7b..2002bb559 100644--- a/os/tests/vm.py+++ b/os/tests/vm.py@@ -391,7 +391,7 @@ 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)+ output, _ = vm.command(user('sh -c ' + shlex.quote('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 && "@@ -620,12 +620,13 @@ if status:vm.command(f"printf %s {shlex.quote(encoded)} | base64 -d > /run/hn-interactive-test.py; chmod 600 /run/hn-interactive-test.py")user = lambda command: 'runuser -u me -- env XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus ' + command_, progress_status = vm.command("grep -q '^def install_with_progress(' /usr/lib/harness-os/install.py", check=False)- vm.command(user('hn new-window -n Install ' + shlex.quote('sudo python3 /run/hn-interactive-test.py')))+ vm.command(user('sh -c ' + shlex.quote('hn new-window -P -F "#{pane_id}" -n Install '+ + shlex.quote('sudo python3 /run/hn-interactive-test.py') + ' > /tmp/hn-install-pane')))transcript = []def wait_screen(pattern, timeout=30):command = ('for n in $(seq 1 ' + str(timeout * 2) + '); do '- 'hn capture-pane -p > /tmp/hn-install-screen; '+ 'hn capture-pane -p -t "$(cat /tmp/hn-install-pane)" > /tmp/hn-install-screen || exit 1; ''grep -Eq ' + shlex.quote(pattern) + ' /tmp/hn-install-screen && exit 0; ''test ! -e /run/hn-interactive-status || exit 1; sleep .5; done; exit 1')_, status = vm.command(user('sh -c ' + shlex.quote(command)), timeout=timeout + 15, check=False)@@ -818,6 +819,15 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'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')result['checks'].append('Offline installer completed on disposable disk')+ if config['encrypt']:+ # Retain costs, not keyslot salts/digests or the full encrypted header.+ script = ('import json,sys; d=json.load(sys.stdin); k=d["keyslots"]["0"]["kdf"]; '+ 'print(json.dumps({key:k[key] for key in ["type","time","memory","cpus"]}))')+ vm.command('cryptsetup luksDump --dump-json-metadata /dev/vda3 | python3 -c '+ + shlex.quote(script) + ' > /tmp/hn-install-pbkdf.json')+ result['installed_pbkdf'] = json.loads(vm.read_file('/tmp/hn-install-pbkdf.json'))+ assert result['installed_pbkdf']['type'] == 'argon2id', 'Encryption must retain Argon2id'+ assert result['installed_pbkdf']['time'] >= 4, 'Encryption must retain benchmarked iterations'vm.command('sync')vm.stop()vm.start(live=False)@@ -836,6 +846,12 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'result['installed_hn_ready_seconds_including_test_login'] = round(time.monotonic() - vm.started, 3)result['installed_keyboard_readiness'] = check_graphical_keyboard(vm, 'installed')result['checks'].append('Installed graphical hn accepts physical-keyboard shell input, returns output and returns home after closing the pane')+ if config['encrypt']:+ installed = json.loads(vm.read_file('/var/lib/harness-os/install.json'))+ budget = installed['pbkdf_memory_limit_kib']+ assert 64 * 1024 <= result['installed_pbkdf']['memory'] <= budget <= 1024 * 1024+ result['pbkdf_memory_limit_kib'] = budget+ result['checks'].append('Encrypted installation after the agent trial retains benchmarked Argon2id within its RAM budget and unlocks after reboot')vm.command('test "$(id -un)" = ' + shlex.quote(config['username']) +' && test "$HOME" = ' + shlex.quote('/home/' + config['username']) +' && test "$(uname -n)" = ' + shlex.quote(config['hostname']))diff --git a/tui/src/app.rs b/tui/src/app.rsindex 20f65fcaf..db185fe99 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -5275,7 +5275,10 @@ impl App {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()));+ // The welcome reply may arrive after another terminal is requested.+ // Fill its original tab instead of whichever tab is now active.+ let tab = self.tab().id.clone();+ crate::input::new_shell_from(self, None, Placement::Fill(tab), None, Some("/usr/bin/hn-os welcome".into()));} else { self.shell_asked = true; }return;}diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex 6ead92f7d..35a9560f2 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -164,7 +164,8 @@ const dial = { said: {}, replies: [], messages: [] }const counts = {}const welcomeTest = process.env.MOCK_WELCOME === '1'if (welcomeTest && !(port >= 19780 && port <= 19789)) throw new Error('unsafe welcome test port')-const welcome = { history: 'loading', delay: 0, searches: [] }+const welcome = { history: 'loading', delay: 0, searches: [], holdTerminals: false, pendingTerminals: 0 }+const welcomeTerminalReplies = []if (welcomeTest) { agents[LOCAL] = []; agents[REMOTE] = [] }const windows = new Set()// Opt-in faults for reconnect.py. No real daemon or agent is involved.@@ -191,7 +192,14 @@ const server = http.createServer((req, res) => {if (req.method === 'GET') return json(res, welcome)let body = ''req.on('data', (part) => { body += part })- req.on('end', () => { const update = JSON.parse(body); Object.assign(welcome, update); json(res, welcome) })+ req.on('end', () => {+ const { releaseTerminal, ...update } = JSON.parse(body)+ Object.assign(welcome, update)+ if (releaseTerminal === 'first') welcomeTerminalReplies.shift()?.()+ if (releaseTerminal === 'last') welcomeTerminalReplies.pop()?.()+ welcome.pendingTerminals = welcomeTerminalReplies.length+ json(res, welcome)+ })return}if (layoutTest && req.url === '/test/layout') {@@ -489,6 +497,11 @@ wss.on('connection', (ws) => {const outcome = { state: 'created', agent: created }creationReceipts.set(receiptKey, { fingerprint, outcome, pendingChecks: payload.projectName === 'lose-reply' ? 1 : 0 })if (payload.projectName === 'lose-reply') return ws.terminate()+ if (welcomeTest && welcome.holdTerminals && payload.engine === 'terminal') {+ welcomeTerminalReplies.push(() => reply({ creationId: payload.creationId, ...outcome }))+ welcome.pendingTerminals = welcomeTerminalReplies.length+ return+ }if (welcomeTest && welcome.delay && payload.engine !== 'terminal') return setTimeout(() => reply({ creationId: payload.creationId, ...outcome }), welcome.delay)return reply({ creationId: payload.creationId, ...outcome })}diff --git a/tui/tests/welcome.py b/tui/tests/welcome.pyindex 480cf98ef..1c5fa1bae 100644--- a/tui/tests/welcome.py+++ b/tui/tests/welcome.py@@ -260,6 +260,50 @@ try:keys('Escape'); hn('kill-window')print('PASS welcome: discovery recovery, browse all, existing-session resume and explicit terminal', flush=True)+ # A USB welcome can finish after a person has already requested another+ # terminal. Release both replies in each order: neither may steal the other's+ # window, change current focus, or make the CLI creation request fail.+ for order in ['first', 'last']:+ hn('kill-server', ok=False)+ tmux('kill-server')+ fresh = BASE / ('usb-startup-' + order)+ fresh.mkdir()+ ENV.update(HOME=str(fresh), HN_TMPDIR=str(fresh), HARNESS_OS='1', HARNESS_OS_LIVE='1',+ ADAPTER_DATA_DIR=str(BASE / '.harness/cli/data'))+ state('welcome', {'holdTerminals': True})+ launch()+ wait(lambda: state('welcome')['pendingTerminals'] == 1, 'USB welcome creation held')+ first_window = window()+ creation = subprocess.Popen(+ [str(HN), '-L', PREFIX, '--port', str(PORT), '-f', '/dev/null',+ 'new-window', '-n', 'early-terminal', 'printf terminal-ready'],+ env=ENV, cwd=PROJECT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ try:+ wait(lambda: state('welcome')['pendingTerminals'] == 2, 'concurrent terminal creation held')+ second_window = window()+ assert first_window != second_window+ state('welcome', {'releaseTerminal': order})+ expected_window = first_window if order == 'first' else second_window+ wait(lambda: hn('display', '-p', '-t', expected_window, '#{window_panes}') == '1',+ 'first completion belongs to its originating window')+ assert window() == second_window, 'completion stole focus'+ state('welcome', {'releaseTerminal': 'first'})+ stdout, stderr = creation.communicate(timeout=5)+ assert creation.returncode == 0, (stdout, stderr)+ wait(lambda: hn('display', '-p', '-t', first_window, '#{window_panes}') == '1', 'USB pane placed')+ assert hn('display', '-p', '-t', second_window, '#{window_panes}') == '1'+ for target, command in [(first_window, '/usr/bin/hn-os welcome'),+ (second_window, 'printf terminal-ready')]:+ actual = hn('display', '-p', '-t', target, '#{pane_start_command}')+ assert shlex.split(actual) == [command], (order, target, actual, command)+ assert window() == second_window+ finally:+ if creation.poll() is None:+ creation.kill(); creation.communicate(timeout=5)+ state('welcome', {'holdTerminals': False})+ ENV.pop('HARNESS_OS'); ENV.pop('HARNESS_OS_LIVE'); ENV.pop('ADAPTER_DATA_DIR')+ print('PASS welcome: USB startup and concurrent terminal creation stay in their own windows in both reply orders', flush=True)+# A new user can arrive without the daemon. Keep the task, explain how to connect,# and let Open Terminal use a real local PTY without executing any draft text.hn('kill-server', ok=False)