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
Fix fresh-install and New Harness launch failures (#516)
Dee93a874912267
diff --git a/cli/scripts/install.sh b/cli/scripts/install.shindex 358b12c95..417f5cde8 100755--- a/cli/scripts/install.sh+++ b/cli/scripts/install.sh@@ -93,6 +93,26 @@ HN_LAUNCHER="$BIN_DIR/hn"# Shared by every download in this file — tmux in step 1 and Node in step 2 — so both manifests are# read by one implementation. Everything here must run in plain POSIX sh: there is no Node yet.+# Retry interrupted connections without requiring a recent curl's --retry-all-errors.+# Buffer manifest stdout per attempt: a partial response must never prefix the next JSON document.+download() {+ for _download_attempt in 1 2 3; do+ if _download_stdout="$(curl -fsSL "$@" --connect-timeout 20 --max-time 600)"; then+ printf '%s' "$_download_stdout"+ return 0+ else+ _download_status=$?+ fi+ case "$_download_status" in+ 6|7|18|28|35|52|55|56|92) ;; # DNS, connection, partial transfer, timeout, TLS reset, HTTP/2+ *) return "$_download_status" ;; # HTTP refusal, certificate verification, local file error+ esac+ [ "$_download_attempt" -lt 3 ] || return "$_download_status"+ echo " ▸ Connection interrupted; retrying download ($((_download_attempt + 1))/3)…" >&2+ sleep 2+ done+}+# sha256 is the one tool that genuinely differs between the two platforms; the pair smooths it over.sha256_of() {if command -v shasum >/dev/null 2>&1; then@@ -181,7 +201,7 @@ install_hn() {echo " ✗ No hn build is published for $(uname -s)/$(uname -m)." >&2return 1}- tui_manifest="$(curl -fsSL "$TUI_METADATA_URL")" || {+ tui_manifest="$(download "$TUI_METADATA_URL")" || {echo " ✗ Could not fetch the hn manifest: $TUI_METADATA_URL" >&2return 1}@@ -196,7 +216,7 @@ install_hn() {mkdir -p "$(dirname "$TUI_BIN")"tui_staging="$TUI_BIN.$$.tmp"echo " ▸ downloading hn${tui_version:+ $tui_version} ($platform)…"- if ! curl -fsSL "$tui_url" -o "$tui_staging"; then+ if ! download "$tui_url" -o "$tui_staging"; thenecho " ✗ Could not download $tui_url" >&2rm -f "$tui_staging"return 1@@ -224,7 +244,7 @@ install_managed_grid() {echo " ✗ No managed grid is published for $(uname -s)/$(uname -m)." >&2return 1}- grid_manifest="$(curl -fsSL "$GRID_METADATA_URL")" || {+ grid_manifest="$(download "$GRID_METADATA_URL")" || {echo " ✗ Could not fetch the grid manifest: $GRID_METADATA_URL" >&2return 1}@@ -245,7 +265,7 @@ install_managed_grid() {rm -rf "$grid_staging"mkdir -p "$grid_staging"echo " ▸ downloading grid $grid_version ($platform)…"- if ! curl -fsSL "$grid_url" -o "$grid_staging/grid.tar.gz"; then+ if ! download "$grid_url" -o "$grid_staging/grid.tar.gz"; thenecho " ✗ Could not download $grid_url" >&2rm -rf "$grid_staging"return 1@@ -326,7 +346,7 @@ install_managed_tmux() {;;esacecho "▸ Installing the managed tmux into $RUNTIME_DIR"- tmux_manifest="$(curl -fsSL "$TMUX_METADATA_URL")" || {+ tmux_manifest="$(download "$TMUX_METADATA_URL")" || {echo "✗ Could not fetch the tmux manifest: $TMUX_METADATA_URL" >&2echo " Install tmux yourself (brew install tmux), then retry." >&2exit 22@@ -349,7 +369,7 @@ install_managed_tmux() {mkdir -p "$tmux_staging"trap 'rm -rf "$tmux_staging"' EXIT INT TERMecho " ▸ downloading tmux $tmux_version ($platform)…"- curl -fsSL "$tmux_url" -o "$tmux_staging/tmux.tar.gz" || {+ download "$tmux_url" -o "$tmux_staging/tmux.tar.gz" || {echo "✗ Could not download $tmux_url" >&2exit 22}@@ -607,7 +627,7 @@ if [ -z "$NODE_BIN" ]; thenecho "▸ Installing the Harness Node runtime into $RUNTIME_DIR"echo " The CLI runs on its own Node so it behaves the same from a terminal and from the app."echo " Your system Node, nvm and Homebrew are not read or changed."- runtime_manifest="$(curl -fsSL "$RUNTIME_METADATA_URL")" || {+ runtime_manifest="$(download "$RUNTIME_METADATA_URL")" || {echo "✗ Could not fetch the Node runtime manifest: $RUNTIME_METADATA_URL" >&2exit 1}@@ -632,7 +652,7 @@ if [ -z "$NODE_BIN" ]; then# complete would be worse than no runtime at all.trap 'rm -rf "$node_staging"' EXIT INT TERMecho " ▸ downloading Node $node_version ($node_platform)…"- curl -fsSL "$node_url" -o "$node_staging/node.tar.gz" || {+ download "$node_url" -o "$node_staging/node.tar.gz" || {echo "✗ Could not download $node_url" >&2exit 1}diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 80d638a2f..58cf25ce6 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1445,6 +1445,31 @@ describe('BackendSocket outbound queue', () => {}})+ it('explains invalid repository choices without echoing credentials or preparing a folder', async () => {+ const socket = new BackendSocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:invalid-project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })+ const prepare = vi.spyOn(projectFolder, 'prepareProjectFolder')+ const create = vi.fn()+ socket.onCreateAgent = create+ try {+ socket.handleLocalFrame('local:invalid-project', { type: 'agent_create', payload: {+ requestId: 'invalid', creationId: randomUUID(), engine: 'codex', projectSource: 'remote',+ repositoryUrl: 'https://[email protected]/owner/repo',+ } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_create_result', payload: {+ requestId: 'invalid', error: 'INVALID_REPOSITORY',+ detail: 'Enter a GitHub HTTPS or SSH URL, or owner/repository.',+ } }))+ expect(JSON.stringify(frames)).not.toContain('private-token')+ expect(prepare).not.toHaveBeenCalled()+ expect(create).not.toHaveBeenCalled()+ } finally {+ await socket.unregisterLocalClient('local:invalid-project')+ await socket.stop()+ }+ })+it.each([{ projectSource: 'remote', repositoryUrl: 'owner/repo' },{ projectSource: 'worktree', gitSource: '/remote/repo', branchRef: 'refs/heads/main' },diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex f4f43ad8e..950b4cdc2 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -2652,7 +2652,9 @@ export class BackendSocket {let projectFoldertry { projectFolder = parseProjectFolder(payload) }catch (error) {- reply(type, requestId, { error: error instanceof ProjectFolderError ? error.code : 'INVALID_PROJECT_SOURCE' }); return+ reply(type, requestId, error instanceof ProjectFolderError+ ? { error: error.code, detail: error.message }+ : { error: 'INVALID_PROJECT_SOURCE' }); return}// A terminal opens where a terminal app would — the home directory — when the client names// no folder; every other engine works IN a folder and must be told which.diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsindex 69793adc2..4ccd20eca 100644--- a/cli/src/lib/terminalStreamManager.spec.ts+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -264,6 +264,43 @@ describe('TerminalStreamManager', () => {expect(stream.sizes.at(-1)).toEqual({ cols: 140, rows: 50 })})+ it.each([[1, 1], [30, 30], [80, 8], [300, 120]])(+ 'opens and resizes a terminal at its actual %i×%i pane size', async (cols, rows) => {+ const open = vi.spyOn(terminals, 'openStream')+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'small', protocolVersion: 3, agentId: 'agent-1', cols, rows,+ })+ expect(sent[0].type).toBe('terminal_ready')+ expect(open.mock.calls[0][1]).toEqual({ cols, rows })+ const streamId = sent[0].payload.streamId+ await manager.handleFrame('web-1', 'terminal_resize', {+ streamId, resizeSeq: 0, cols: 120, rows: 40,+ })+ await manager.handleFrame('web-1', 'terminal_resize', {+ streamId, resizeSeq: 1, cols, rows,+ })+ expect(stream.sizes).toEqual([{ cols: 120, rows: 40 }, { cols, rows }])+ },+ )++ it.each([[0, 20], [80, 0], [-1, 20], [80, -1], [1.5, 20], [80, 1.5], [301, 20], [80, 121]])(+ 'rejects invalid %i×%i dimensions on open and resize', async (cols, rows) => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'invalid', protocolVersion: 3, agentId: 'agent-1', cols, rows,+ })+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_OPEN_INVALID')+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'valid', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24,+ })+ const streamId = sent.at(-1)!.payload.streamId+ await manager.handleFrame('web-1', 'terminal_resize', { streamId, resizeSeq: 0, cols, rows })+ expect(stream.sizes).toEqual([])+ // A bad size must not consume the sequence number or prevent a later valid resize.+ await manager.handleFrame('web-1', 'terminal_resize', { streamId, resizeSeq: 0, cols: 80, rows: 24 })+ expect(stream.sizes).toEqual([{ cols: 80, rows: 24 }])+ },+ )+it('routes terminal_scroll to the stream handle, and rejects a malformed one', async () => {await manager.handleFrame('web-1', 'terminal_open', {requestId: 'open-scroll', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex 6f06c18b2..1775db305 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -180,7 +180,9 @@ export interface TerminalStreamManagerDeps {function sizeFrom(payload: FramePayload): TerminalStreamSize | null {const cols = Number(payload.cols)const rows = Number(payload.rows)- if (!Number.isSafeInteger(cols) || !Number.isSafeInteger(rows) || cols < 40 || cols > 300 || rows < 12 || rows > 120) return null+ // Split TUI panes can be smaller than a desktop terminal. Preserve their actual size so+ // opening a third pane or shrinking the window does not reject the stream or crop its output.+ if (!Number.isSafeInteger(cols) || !Number.isSafeInteger(rows) || cols < 1 || cols > 300 || rows < 1 || rows > 120) return nullreturn { cols, rows }}diff --git a/cli/src/lib/tmuxStream.real.spec.ts b/cli/src/lib/tmuxStream.real.spec.tsindex 2dc918b24..a05ab3bf3 100644--- a/cli/src/lib/tmuxStream.real.spec.ts+++ b/cli/src/lib/tmuxStream.real.spec.ts@@ -1,9 +1,9 @@import { execFile } from 'node:child_process'-import { mkdtemp, readFile } from 'node:fs/promises'+import { mkdtemp, readFile, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { randomUUID } from 'node:crypto'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import { ENGINES } from '../engines/types.js'import type { RegisteredSession } from './registry.js'import { TerminalStreamManager } from './terminalStreamManager.js'@@ -28,12 +28,27 @@ async function eventually(predicate: () => boolean | Promise<boolean>, timeoutMsrun('TmuxControlStream real tmux', () => {const session = `harness-stream-${randomUUID().slice(0, 8)}`let paneId = ''+ let socketRoot = ''beforeAll(async () => {- paneId = await tmux(['new-session', '-d', '-P', '-F', '#{pane_id}', '-s', session, 'bash', '--noprofile', '--norc'])+ // A managed client must not attach to a developer's existing server of another tmux version.+ socketRoot = await mkdtemp(join(tmpdir(), 'harness-stream-server-'))+ vi.stubEnv('TMUX_TMPDIR', socketRoot)+ vi.stubEnv('TMUX', undefined)+ vi.stubEnv('TMUX_PANE', undefined)})afterAll(async () => {+ await tmux(['kill-server']).catch(() => {})+ vi.unstubAllEnvs()+ await rm(socketRoot, { recursive: true, force: true })+ })++ beforeEach(async () => {+ paneId = await tmux(['new-session', '-d', '-P', '-F', '#{pane_id}', '-s', session, 'bash', '--noprofile', '--norc'])+ })++ afterEach(async () => {await tmux(['kill-session', '-t', session]).catch(() => { /* exact disposable session only */ })})@@ -92,6 +107,28 @@ run('TmuxControlStream real tmux', () => {expect(closedReason === '' || closedReason === 'closed').toBe(true)})+ it('opens and resizes narrow and short panes without flooring them to desktop dimensions', async () => {+ const opened = await TmuxControlStream.open(paneId, { cols: 30, rows: 8 }, {+ onData: () => {}, onClose: () => {},+ })+ expect(opened.state).toBe('succeeded')+ try {+ if (opened.state !== 'succeeded') return+ expect(await tmux(['display-message', '-p', '-t', paneId, '#{pane_width}x#{pane_height}'])).toBe('30x8')+ for (const size of [{ cols: 1, rows: 1 }, { cols: 39, rows: 11 }, { cols: 120, rows: 40 }]) {+ expect((await opened.value.resize(size)).state).toBe('succeeded')+ expect(await tmux(['display-message', '-p', '-t', paneId, '#{pane_width}x#{pane_height}'])).toBe(`${size.cols}x${size.rows}`)+ opened.value.beginSnapshot()+ const snapshot = await opened.value.snapshot()+ expect(snapshot.state).toBe('succeeded')+ if (snapshot.state === 'succeeded') expect(snapshot.value).toMatchObject(size)+ opened.value.endSnapshot()+ }+ } finally {+ if (opened.state === 'succeeded') await opened.value.close()+ }+ })+it('delivers a multi-chunk paste to the pane whole and in order', async () => {// 8 KiB in one writeRaw spans several `send-keys -H` commands (INPUT_CHUNK_BYTES is 2 KiB).// They are pipelined into the control client, so this is the case that would expose either adiff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.tsindex 9e6d5b7cd..78ed3907f 100644--- a/cli/src/lib/tmuxStream.ts+++ b/cli/src/lib/tmuxStream.ts@@ -13,9 +13,9 @@ import {type TmuxRuntimeRef,} from './terminalTypes.js'-const MIN_COLS = 40+const MIN_COLS = 1const MAX_COLS = 300-const MIN_ROWS = 12+const MIN_ROWS = 1const MAX_ROWS = 120// One `send-keys -H` line carries two hex characters plus a space per byte. tmux accepts a command// line built from 8192 such bytes and rejects 16384 with `%error`, so this leaves a 4x margin.diff --git a/cli/src/scripts/install.spec.ts b/cli/src/scripts/install.spec.tsindex 44d68004a..004cc395c 100644--- a/cli/src/scripts/install.spec.ts+++ b/cli/src/scripts/install.spec.ts@@ -1,4 +1,4 @@-import { spawnSync } from "child_process";+import { spawn, spawnSync } from "child_process";import { join } from "path";import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from "fs";import { tmpdir } from "os";@@ -9,6 +9,90 @@ import { TmuxBackend } from "../lib/tmuxBackend.js";// vitest runs from cli/, so this is cli/scripts/install.sh — the file published to the CDN.const installer = join(process.cwd(), "scripts", "install.sh");+describe('installer interrupted downloads', () => {+ it('recovers real truncated HTTP responses without mixing manifest or binary bytes', async () => {+ const { createServer } = await import('node:http');+ const scratch = mkdtempSync(join(tmpdir(), 'harness-download-http-'));+ const bytes = Buffer.from([0, 1, 255, 10, 2, 0, 42, 128]);+ const counts = new Map<string, number>();+ const server = createServer((req, res) => {+ const route = req.url!;+ const count = (counts.get(route) ?? 0) + 1;+ counts.set(route, count);+ const body = route === '/manifest' ? Buffer.from('{"version":"verified"}') : bytes;+ res.writeHead(200, { 'Content-Length': body.length, 'Connection': 'close' });+ res.end(count < 3 ? body.subarray(0, 3) : body);+ });+ try {+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const port = (server.address() as { port: number }).port;+ const source = readFileSync(installer, 'utf8');+ const fn = source.slice(source.indexOf('download() {'), source.indexOf('# sha256 is'));+ const child = spawn('/bin/sh', ['-ec', fn + '\ndownload "$URL/manifest"\ndownload "$URL/binary" -o "$TARGET"'], {+ env: { ...process.env, URL: `http://127.0.0.1:${port}`, TARGET: join(scratch, 'binary') },+ });+ let stdout = '', stderr = '';+ child.stdout.on('data', data => { stdout += data });+ child.stderr.on('data', data => { stderr += data });+ const code = await new Promise<number | null>((resolve, reject) => {+ child.on('error', reject); child.on('close', resolve);+ });+ expect(code, stderr).toBe(0);+ expect(JSON.parse(stdout)).toEqual({ version: 'verified' });+ expect(readFileSync(join(scratch, 'binary'))).toEqual(bytes);+ expect(Object.fromEntries(counts)).toEqual({ '/manifest': 3, '/binary': 3 });+ } finally {+ server.closeAllConnections();+ await new Promise<void>(resolve => server.close(() => resolve()));+ rmSync(scratch, { recursive: true, force: true });+ }+ }, 30_000);++ it.each([6, 7, 18, 28, 35, 52, 55, 56, 92])('retries curl error %i and discards partial manifest output', code => {+ const scratch = mkdtempSync(join(tmpdir(), 'harness-download-'));+ try {+ writeCommand(scratch, 'curl', [+ 'n=0; [ ! -f "$COUNT" ] || n=$(cat "$COUNT")',+ 'n=$((n + 1)); echo "$n" > "$COUNT"',+ `if [ "$n" -lt 3 ]; then printf 'broken partial JSON'; exit ${code}; fi`,+ 'printf \'{"version":"test"}\\n\'',+ ]);+ writeCommand(scratch, 'sleep', ['exit 0']);+ const source = readFileSync(installer, 'utf8');+ const fn = source.slice(source.indexOf('download() {'), source.indexOf('# sha256 is'));+ const result = spawnSync('/bin/sh', ['-c', fn + '\ndownload https://example.invalid/manifest'], {+ encoding: 'utf8', env: { ...process.env, PATH: `${scratch}:/usr/bin:/bin`, COUNT: join(scratch, 'count') },+ });+ expect(result.status).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({ version: 'test' });+ expect(readFileSync(join(scratch, 'count'), 'utf8').trim()).toBe('3');+ expect(result.stderr).toContain('retrying download (3/3)');+ } finally { rmSync(scratch, { recursive: true, force: true }); }+ });++ it.each([[35, 3], [22, 1], [60, 1], [23, 1]])('bounds failures and preserves curl status %i', (code, attempts) => {+ const scratch = mkdtempSync(join(tmpdir(), 'harness-download-fail-'));+ try {+ writeCommand(scratch, 'curl', [+ 'echo "$*" >> "$CALLS"', `printf partial; exit ${code}`,+ ]);+ writeCommand(scratch, 'sleep', ['exit 0']);+ const source = readFileSync(installer, 'utf8');+ const fn = source.slice(source.indexOf('download() {'), source.indexOf('# sha256 is'));+ const result = spawnSync('/bin/sh', ['-c', fn + '\ndownload https://example.invalid/runtime -o "$TARGET"'], {+ encoding: 'utf8', env: { ...process.env, PATH: `${scratch}:/usr/bin:/bin`,+ CALLS: join(scratch, 'calls'), TARGET: join(scratch, 'download') },+ });+ expect(result.status).toBe(code);+ expect(result.stdout).toBe('');+ const calls = readFileSync(join(scratch, 'calls'), 'utf8').trim().split('\n');+ expect(calls).toHaveLength(attempts);+ expect(calls[0]).toContain('--connect-timeout 20 --max-time 600');+ expect(calls[0]).toContain(`-o ${join(scratch, 'download')}`);+ } finally { rmSync(scratch, { recursive: true, force: true }); }+ });+});+const writeCommand = (directory: string, name: string, lines: string[]) => {const path = join(directory, name);writeFileSync(path, ["#!/bin/sh", ...lines, ""].join("\n"));@@ -772,7 +856,7 @@ describe("scripts/install.sh command contract", () => {} finally {rmSync(scratch, { recursive: true, force: true });}- });+ }, 20_000); // Several real shell/package-manager processes, as in the other installer integration checks.// ── the managed grid ──────────────────────────────────────────────────────────────────────────//diff --git a/tui/Cargo.lock b/tui/Cargo.lockindex 15a6a2e3f..a6b62f05d 100644--- a/tui/Cargo.lock+++ b/tui/Cargo.lock@@ -653,7 +653,7 @@ dependencies = [[[package]]name = "harness-tui"-version = "0.1.6"+version = "0.1.7"dependencies = ["alacritty_terminal","crossterm",diff --git a/tui/Cargo.toml b/tui/Cargo.tomlindex 97f69cf1d..90def56b7 100644--- a/tui/Cargo.toml+++ b/tui/Cargo.toml@@ -1,6 +1,6 @@[package]name = "harness-tui"-version = "0.1.6"+version = "0.1.7"edition = "2024"[dependencies]diff --git a/tui/src/app.rs b/tui/src/app.rsindex 0e7dd4047..d7b019411 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -1727,8 +1727,7 @@ impl App {return;};let (cols, rows) = content.unwrap_or((pane.cols, pane.rows));- // Below the daemon's 40×12 the far terminal stays 40×12 and the tile shows the part of it- // around the cursor, as tmux shows a window bigger than its client.+ // The remote terminal follows the actual tile, including narrow or short split panes.let (cols, rows) = pane::stream_size(cols, rows);pane.opening = true;pane.want = (cols, rows);diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rsindex 2a576563e..b53a2dd58 100644--- a/tui/src/new_harness.rs+++ b/tui/src/new_harness.rs@@ -1748,6 +1748,34 @@ mod tests {}}+ #[tokio::test]+ async fn project_error_keeps_its_recovery_instruction_and_action_visible() {+ let mut app = app();+ open(&mut app, None, None);+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ form.error = "Could not start it: “My-First-Claude-Project” already exists. Select that folder from your projects.".into();+ for width in [45, 80, 130] {+ let area = Rect::new(0, 0, width, 38);+ let mut buf = Buffer::empty(area);+ draw(&mut buf, area, &mut form);+ let text: String = (form.area.y..form.area.bottom()).map(|y| {+ (form.area.x + 2..form.area.right() - 2)+ .map(|x| buf[(x, y)].symbol()).collect::<String>().trim().to_string()+ }).collect::<Vec<_>>().join(" ");+ assert!(text.contains("already exists. Select that folder from your projects."), "{text}");+ assert!(form.hits.iter().any(|(_, f)| *f == Field::Create));+ assert_eq!(form.area.intersection(area), form.area);+ }+ form.error = "项目".repeat(100);+ for height in [5, 10, 24] {+ let area = Rect::new(0, 0, 22, height);+ let mut buf = Buffer::empty(area);+ draw(&mut buf, area, &mut form);+ assert_eq!(form.area.intersection(area), form.area);+ assert!(form.hits.iter().any(|(_, f)| *f == Field::Create));+ }+ }+#[tokio::test]async fn terminal_and_agent_options_match_the_launch_contract() {let mut app = app();diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rsindex 83aeb38e4..3354bfcb5 100644--- a/tui/src/new_harness/view.rs+++ b/tui/src/new_harness/view.rs@@ -1,5 +1,28 @@//! Terminal rendering of the compact desktop form.use super::*;+use unicode_segmentation::UnicodeSegmentation;++// Keep the recovery instruction readable, including long project names and wide glyphs.+fn error_lines(text: &str, width: usize) -> Vec<String> {+ let mut lines = Vec::new();+ let mut line = String::new();+ for word in text.split_whitespace() {+ if !line.is_empty() && line.width() + 1 + word.width() > width {+ lines.push(std::mem::take(&mut line));+ }+ if !line.is_empty() {+ line.push(' ');+ }+ for glyph in word.graphemes(true) {+ if !line.is_empty() && line.width() + glyph.width() > width {+ lines.push(std::mem::take(&mut line));+ }+ line.push_str(glyph);+ }+ }+ lines.push(line);+ lines+}fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) {if width == 0 {@@ -52,20 +75,24 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {let (x, y, form_w, form_h) = (r.x, r.y, r.width, r.height);let (child_w, child_h) = (form_w, form_h);let fields = form.fields();+ let errors = error_lines(&form.error, form_w.saturating_sub(4) as usize);+ let error_h = errors.len().min(form_h.saturating_sub(4).max(1) as usize) as u16;form.area = r;if form.child.is_none() || side || !form.child_active {panel(buf, r, base);- let gap = if form_h >= fields.len() as u16 * 2 + 3 {+ let fields_h = form_h - error_h + 1;+ let error_y = r.bottom() - 1 - error_h;+ let gap = if fields_h >= fields.len() as u16 * 2 + 3 {2} else {1};- let capacity = ((form_h.saturating_sub(5) / gap) + 1) as usize;+ let capacity = ((fields_h.saturating_sub(5) / gap) + 1) as usize;let focus = fields.iter().position(|f| *f == form.focus).unwrap_or(0);let skip = focus.saturating_sub(capacity - 1);for (row, field) in fields.iter().skip(skip).take(capacity).enumerate() {- let fy = r.y + 2 + row as u16 * gap;- if fy >= r.bottom() - 2 {+ let fy = r.y + if form_h < 5 { 0 } else { 2 } + row as u16 * gap;+ if fy >= error_y {break;}let active = *field == form.focus;@@ -102,18 +129,10 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {form.hits.push((Rect::new(r.x + 1, fy, r.width - 2, 1), *field));}- put(- buf,- r.x + 2,- r.bottom() - 2,- r.width - 4,- &form.error,- if form.error.is_empty() {- muted- } else {- base.patch(theme::fg(theme::DANGER))- },- );+ for (row, line) in errors.iter().take(error_h as usize).enumerate() {+ put(buf, r.x + 2, error_y + row as u16, r.width - 4, line,+ base.patch(theme::fg(theme::DANGER)));+ }}if !side && !form.child_active {return None;diff --git a/tui/tests/fresh-user-journeys.py b/tui/tests/fresh-user-journeys.pynew file mode 100644index 000000000..f155b35db--- /dev/null+++ b/tui/tests/fresh-user-journeys.py@@ -0,0 +1,235 @@+"""Scenarios for fresh-user.py: real TUI actions, real agents and real folders.++Run `python3 tui/tests/fresh-user.py run` to install and exercise everything.+Set HN_FRESH_USER_CLI / HN_FRESH_USER_BINARY to test local release candidates.+No vendor credentials are copied: success means reaching the real onboarding UI.+The daemon API is used only to verify state, never to perform a product action.+"""+from pathlib import Path+import subprocess+++def git(u, path, *args):+ return subprocess.check_output(['git', '-C', str(path), *args], env=u.env,+ text=True, stderr=subprocess.STDOUT, timeout=20).strip()+++def repository(u, name, branch='main', committed=True):+ path = u.home / 'Projects' / name+ path.mkdir(parents=True)+ git(u, path, 'init', '-b', branch)+ git(u, path, 'config', 'user.name', 'Harness Test')+ git(u, path, 'config', 'user.email', '[email protected]')+ if committed:+ (path / 'README.md').write_text('Fresh-user Git fixture\n')+ git(u, path, 'add', 'README.md')+ git(u, path, 'commit', '-m', 'Initial fixture')+ return path+++def options(u):+ u.field('Options')+ u.wait('Worktree')+++def rejected(u, text, label):+ count = len(u.status()['sessions'])+ u.keys('Enter')+ u.wait(text, 90)+ assert len(u.status()['sessions']) == count, 'A refused launch created an agent'+ u.record(label)+++def core(u):+ u.wait('C-b N new', 60)+ assert not u.status()['signedIn']+ for name in ['codex', 'claude']:+ assert not (u.home / '.local/bin' / name).exists()+ u.record('signed-out-start')+ u.form()+ u.launch('codex', 'codex-auto-install-default-folder')+ assert (u.home / '.local/bin/codex').exists()++ u.form('claude')+ u.project('new folder', 'My First Claude Project')+ session = u.launch('claude', 'claude-auto-install-named-folder')+ assert session['cwd'] == '~/harnesses/My-First-Claude-Project'+ assert (u.home / '.local/bin/claude').exists()++ folder = u.home / "Projects/Notes & 'quotes' café"+ folder.mkdir(parents=True)+ (folder / 'keep-me.txt').write_text('fresh-user folder fixture\n')+ u.form('terminal')+ u.project('open folder', str(folder))+ before = {s['id'] for s in u.status()['sessions']}+ u.keys('Enter')+ u.check(lambda: len([s for s in u.status()['sessions'] if s['id'] not in before]) == 1,+ 'Third pane created', 60)+ # Keep all three splits visible to catch sub-40-column terminal_open regressions.+ u.wait('Terminal on', 60)+ assert 'TERMINAL_OPEN_INVALID' not in u.screen()+ u.keys('C-c')+ u.text("printf 'OPEN_%s_OK\\n' FOLDER; pwd > ~/open-folder-cwd.txt")+ u.keys('Enter')+ u.wait('OPEN_FOLDER_OK')+ assert (u.home / 'open-folder-cwd.txt').read_text().strip() == str(folder)+ assert (folder / 'keep-me.txt').read_text() == 'fresh-user folder fixture\n'+ u.record('open-folder-special-characters-third-pane')+ u.zoom()+ u.close_view()+++def folders(u):+ u.form('codex')+ u.project('new folder', 'My First Claude Project')+ rejected(u, 'Select that folder', 'existing-folder-protected')+ u.keys('Escape')+ u.form()+ u.wait('Select that folder')+ u.record('failed-draft-restored')+ u.project('new folder', 'Retry Project')+ session = u.launch('codex', 'folder-error-corrected', double_enter=True)+ assert session['cwd'] == '~/harnesses/Retry-Project'+ u.close_view()++ # Defaults allocate another folder rather than sharing one created in the same minute.+ names = set((u.home / 'harnesses').iterdir())+ u.form('codex')+ u.project('new folder', '')+ session = u.launch('codex', 'blank-folder-name-unique')+ assert len(set((u.home / 'harnesses').iterdir()) - names) == 1+ u.close_view()++ # Invalid paths remain in the picker and can be corrected without dismissing the form.+ u.form('codex')+ u.choose('Project', 'open folder', 'Search projects')+ u.wait('Choose a machine'); u.keys('Enter'); u.wait('Use this folder')+ u.keys('C-l', 'C-u'); u.text(str(u.home / 'does-not-exist')); u.keys('Enter')+ u.wait('Could not')+ u.record('missing-folder-browse-error')+ u.keys('C-l', 'C-u'); u.text('~/harnesses/Retry-Project'); u.keys('Enter')+ u.wait('Use this folder'); u.keys('Enter')+ session = u.launch('codex', 'tilde-path-recovery-agent-reuse')+ assert session['cwd'] == '~/harnesses/Retry-Project'+ u.close_view()+++def clones(u):+ u.form('codex')+ u.project('clone', 'https://example.invalid/repo')+ rejected(u, 'Enter a GitHub', 'invalid-repository-actionable')+ u.project('clone', 'octocat/hn-fresh-user-no-such-repository-20260930')+ rejected(u, 'Could not', 'missing-repository-rejected')+ assert not list((u.home / 'harnesses').glob('.harness-clone-*'))+ u.project('clone', 'octocat/Hello-World')+ session = u.launch('codex', 'clone-owner-repository')+ repo = u.home / 'harnesses/Hello-World'+ assert session['cwd'] == '~/harnesses/Hello-World'+ assert git(u, repo, 'remote', 'get-url', 'origin') == 'https://github.com/octocat/Hello-World.git'+ assert (repo / 'README').is_file()+ head = git(u, repo, 'rev-parse', 'HEAD')+ u.close_view()+ u.form('claude')+ u.project('clone', 'https://github.com/octocat/Hello-World.git')+ rejected(u, 'Select that folder', 'clone-collision-protected')+ assert git(u, repo, 'rev-parse', 'HEAD') == head+ # A separate small public repository exercises HTTPS success too.+ u.project('clone', 'https://github.com/octocat/Spoon-Knife.git')+ u.launch('claude', 'clone-https-repository')+ assert (u.home / 'harnesses/Spoon-Knife/.git').is_dir()+ u.close_view()+++def worktrees(u):+ repo = repository(u, 'Main Repository')+ git(u, repo, 'branch', 'feature')+ (repo / 'README.md').write_text('Uncommitted user work\n')+ u.form('codex'); u.project('open folder', str(repo))+ u.check(lambda: 'Checking Git' not in u.screen(), 'Git discovery')+ session = u.launch('codex', 'default-worktree-from-main')+ path = Path(session['cwd'].replace('~', str(u.home), 1))+ assert path != repo and '/worktrees/' in str(path)+ assert git(u, path, 'rev-parse', 'HEAD') == git(u, repo, 'rev-parse', 'main')+ assert (repo / 'README.md').read_text() == 'Uncommitted user work\n'+ assert (path / 'README.md').read_text() == 'Fresh-user Git fixture\n'+ u.close_view()++ u.form('claude'); u.project('open folder', str(repo)); options(u)+ u.choose('Branch', 'feature', 'Search or create a branch')+ session = u.launch('claude', 'existing-branch-worktree', click_create=True)+ path = Path(session['cwd'].replace('~', str(u.home), 1))+ assert '/worktrees/Main Repository/' in str(path)+ assert git(u, path, 'branch', '--show-current') == 'feature'+ assert (repo / 'README.md').read_text() == 'Uncommitted user work\n'+ u.close_view()++ empty = repository(u, 'Empty Repository', committed=False)+ u.form('codex'); u.project('open folder', str(empty))+ rejected(u, 'Choose a branch', 'empty-repository-worktree-guidance')+ options(u); u.field('Worktree')+ session = u.launch('codex', 'empty-repository-worktree-off', click_create=True)+ assert session['cwd'] == '~/Projects/Empty Repository'+ assert not (empty / '.git/refs/heads/main').exists()+ u.close_view()+++def narrow_cancel(u):+ before = len(u.status()['sessions'])+ u.form('claude'); u.project('new folder', 'Keep Draft')+ for width, height in [(80, 24), (45, 14), (22, 5), (1, 1), (130, 38)]:+ u.outer('resize-window', '-t', 'user', '-x', str(width), '-y', str(height))+ u.check(lambda: bool(u.native('display-message', '-p', '#{window_panes}')), 'TUI remains responsive')+ u.wait('Keep Draft')+ u.keys('Escape'); u.form(); u.wait('Keep Draft')+ u.record('resize-and-cancel-preserve-draft')+ u.keys('Escape')+ assert len(u.status()['sessions']) == before+ assert not (u.home / 'harnesses/Keep-Draft').exists()+++def git_edges(u):+ master = repository(u, 'Master Repository', branch='master')+ u.form('codex'); u.project('open folder', str(master))+ rejected(u, 'Choose a branch', 'repository-without-main-guidance')+ options(u); u.choose('Branch', 'master', 'Search or create a branch')+ session = u.launch('codex', 'explicit-master-worktree', click_create=True)+ path = Path(session['cwd'].replace('~', str(u.home), 1))+ assert git(u, path, 'rev-parse', 'HEAD') == git(u, master, 'rev-parse', 'master')+ u.close_view()++ repo = repository(u, 'Dirty Repository')+ git(u, repo, 'branch', 'feature')+ (repo / 'README.md').write_text('Unsaved user work\n')+ u.form('codex'); u.project('open folder', str(repo)); options(u)+ u.field('Worktree'); u.choose('Branch', 'new-topic', 'Search or create a branch')+ session = u.launch('codex', 'new-branch-in-existing-folder', click_create=True)+ assert session['cwd'] == '~/Projects/Dirty Repository'+ assert git(u, repo, 'branch', '--show-current') == 'new-topic'+ assert (repo / 'README.md').read_text() == 'Unsaved user work\n'+ u.close_view()++ u.form('codex'); u.project('open folder', str(repo)); options(u)+ u.field('Worktree'); u.choose('Branch', 'feature', 'Search or create a branch')+ rejected(u, 'uncommitted changes', 'dirty-branch-switch-protected')+ assert git(u, repo, 'branch', '--show-current') == 'new-topic'+ assert (repo / 'README.md').read_text() == 'Unsaved user work\n'+ u.field('Worktree')+ u.choose('Branch', 'feature', 'Search or create a branch')+ session = u.launch('codex', 'dirty-switch-recovered-with-worktree', click_create=True)+ path = Path(session['cwd'].replace('~', str(u.home), 1))+ assert git(u, path, 'branch', '--show-current') == 'feature'+ assert (repo / 'README.md').read_text() == 'Unsaved user work\n'+ u.close_view()+++def run(u, names):+ cases = dict(core=core, folders=folders, clones=clones, worktrees=worktrees,+ git_edges=git_edges, narrow=narrow_cancel)+ for name in names or cases:+ print('RUN ' + name, flush=True)+ try:+ cases[name](u)+ except Exception:+ u.snapshot('failure-' + name)+ raise+ print('Evidence: ' + str(u.root / 'results.json'), flush=True)diff --git a/tui/tests/fresh-user.py b/tui/tests/fresh-user.pynew file mode 100644index 000000000..5f84799ea--- /dev/null+++ b/tui/tests/fresh-user.py@@ -0,0 +1,274 @@+#!/usr/bin/env python3+"""Drive the installed hn UI in a disposable, signed-out home with real agents.++`fresh-user.py start` runs the public curl installer and opens hn in a private+terminal. Subsequent commands use the printed --state path. All product actions+are terminal keys or mouse input; daemon requests are read-only verification.+Keep the state and captures as evidence, and run `stop` to close only this rig.+"""+import argparse+import http.client+import json+import os+from pathlib import Path+import re+import shlex+import shutil+import socket+import subprocess+import tempfile+import time+++class User:+ def __init__(self, state):+ self.path = Path(state).resolve()+ self.state = json.loads(self.path.read_text())+ self.root = self.path.parent+ assert self.root.name.startswith('hn-user-') and self.state['root'] == str(self.root)+ self.env = self.state['env']+ self.home = Path(self.env['HOME'])+ assert self.home.parent == self.root++ def outer(self, *args, check=True):+ return subprocess.run([self.state['tmux'], '-S', str(self.root / 'outer.sock'), *args],+ env=self.env, cwd=self.home, capture_output=True, text=True,+ check=check, timeout=15)++ def screen(self, ansi=False):+ return self.outer('capture-pane', '-p', *(['-e'] if ansi else []), '-t', 'user').stdout++ def keys(self, *keys):+ self.outer('send-keys', '-t', 'user', *keys)+ self.settle()++ def settle(self):+ previous, changed = None, time.monotonic()+ deadline = changed + 5+ while time.monotonic() < deadline:+ # Both the popup and pane chrome can be borderless. Ignore the animated+ # braille spinners while waiting for text and mouse targets to settle.+ signature = tuple(re.sub(r'[\u2800-\u28ff]', ' ', line)+ for line in self.screen().splitlines())+ if signature != previous:+ previous, changed = signature, time.monotonic()+ elif time.monotonic() - changed >= .15:+ return+ time.sleep(.025)+ raise AssertionError('Popup did not settle\n' + self.screen())++ def native(self, *args):+ return subprocess.check_output([str(self.home / '.harness/bin/harness-tui'), *args],+ env=self.env, cwd=self.home, text=True, timeout=15).strip()++ def zoom(self):+ if self.native('display-message', '-p', '#{window_zoomed_flag}') != '1':+ self.keys('C-b', 'z')++ def text(self, text):+ self.outer('send-keys', '-l', '-t', 'user', text)++ def click(self, x, y):+ for suffix in ('M', 'm'):+ self.outer('send-keys', '-H', '-t', 'user',+ *[f'{b:02x}' for b in f'\x1b[<0;{x+1};{y+1}{suffix}'.encode()])++ def field(self, label):+ self.settle()+ for y, line in enumerate(self.screen().splitlines()):+ match = re.search(r'(?<![^\s│›])(' + re.escape(label) + r') {2,}', line)+ if match:+ self.click(match.start(1), y)+ self.settle()+ return+ raise AssertionError(f'No visible field {label}\n{self.screen()}')++ def wait(self, text, seconds=30):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ screen = self.screen()+ # Messages can wrap across popup rows, with the working panes visible beside them.+ popup = ' '.join(line[line.index('│') + 1:line.rindex('│')].strip()+ for line in screen.splitlines() if line.count('│') >= 2)+ if text in screen or text in popup or text in ' '.join(screen.split()):+ return screen+ time.sleep(.1)+ raise AssertionError(f'Did not see {text!r}\n{screen}')++ def snapshot(self, name):+ assert re.fullmatch(r'[a-zA-Z0-9_-]+', name)+ directory = self.root / 'captures'+ directory.mkdir(exist_ok=True)+ for ansi, suffix in [(False, 'txt'), (True, 'ansi')]:+ (directory / f'{name}.{suffix}').write_text(self.screen(ansi))++ def check(self, predicate, label, seconds=30):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ value = predicate()+ if value:+ return value+ time.sleep(.1)+ raise AssertionError(label + '\n' + self.screen())++ def record(self, name, **details):+ self.snapshot(name)+ path = self.root / 'results.json'+ rows = json.loads(path.read_text()) if path.exists() else {}+ rows[name] = dict(result='pass', evidence=f'captures/{name}.txt', **details)+ path.write_text(json.dumps(rows, indent=2) + '\n')+ print('PASS ' + name, flush=True)++ def choose(self, label, query, hint):+ self.field(label)+ self.wait(hint)+ self.text(query)+ self.keys('Enter')++ def form(self, engine=None):+ self.keys('C-b', 'N')+ self.wait('Options')+ if engine:+ self.choose('Agent', engine, 'Search agents')++ def project(self, action, value):+ self.choose('Project', action, 'Search projects')+ self.wait('Choose a machine')+ self.keys('Enter')+ if action == 'open folder':+ self.wait('Use this folder')+ self.keys('C-l', 'C-u')+ self.wait('/path/to/project')+ self.text(value)+ self.keys('Enter')+ self.wait('Use this folder')+ self.keys('Enter')+ else:+ self.wait('Folder name' if action == 'new folder' else 'GitHub URL')+ self.text(value)+ self.keys('Enter')+ self.wait('Options')++ def launch(self, engine, label, double_enter=False, click_create=False):+ before = {s['id'] for s in self.status()['sessions']}+ if click_create:+ self.field('New Harness')+ else:+ self.keys(*(['Enter', 'Enter'] if double_enter else ['Enter']))+ added = self.check(lambda: [s for s in self.status()['sessions'] if s['id'] not in before],+ 'A new harness should become available', 180)+ assert len(added) == 1 and added[0]['engine'] == engine, added+ self.check(lambda: not re.search(r'(?<![^\s│›])Options {2,}', self.screen()), 'Form closes after launch')+ self.zoom()+ markers = {'codex': ['Welcome to Codex'],+ 'claude': ['Choose the text style', 'Select login method'],+ 'terminal': ['Terminal on']}[engine]+ self.check(lambda: any(marker in self.screen() for marker in markers),+ 'Real agent onboarding or terminal prompt', 180)+ assert 'TERMINAL_OPEN_INVALID' not in self.screen()+ self.record(label, engine=engine, cwd=added[0]['cwd'])+ return added[0]++ def close_view(self):+ self.keys('C-b', 'x')+ self.wait('kill-pane')+ self.keys('y')++ def status(self):+ conn = http.client.HTTPConnection('localhost', timeout=3)+ conn.sock = socket.socket(socket.AF_UNIX)+ conn.sock.settimeout(3)+ try:+ conn.sock.connect(str(self.home / '.harness/cli/data' / f'daemon-{self.env["PORT"]}.sock'))+ conn.request('GET', '/api/status')+ response = conn.getresponse()+ assert response.status == 200+ return json.load(response)+ finally:+ conn.close()++ def stop(self):+ native = self.home / '.harness/bin/harness-tui'+ if native.exists():+ subprocess.run([str(native), 'kill-server'], env=self.env, cwd=self.home,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20)+ launcher = self.home / '.local/bin/harness'+ if launcher.exists():+ subprocess.run([str(launcher), 'stop'], env=self.env, cwd=self.home,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=25)+ self.outer('kill-server', check=False)+ marker = self.home / '.harness/runtime/current-tmux'+ if marker.exists():+ subprocess.run([marker.read_text().strip(), 'kill-server'], env=self.env,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)+++def start():+ root = Path(tempfile.mkdtemp(prefix='hn-user-', dir='/tmp')).resolve()+ home = root / 'home'+ for path in (home, root / 'tmp', root / 'tmux', root / 'hn'):+ path.mkdir(mode=0o700)+ tmux = shutil.which('tmux')+ assert tmux, 'tmux is needed only to drive the outer test terminal'+ with socket.socket() as probe:+ probe.bind(('127.0.0.1', 0))+ port = probe.getsockname()[1]+ env = dict(HOME=str(home), TMPDIR=str(root / 'tmp'), PATH='/usr/bin:/bin:/usr/sbin:/sbin',+ SHELL='/bin/zsh' if Path('/bin/zsh').exists() else '/bin/bash',+ LANG='en_US.UTF-8', TERM='xterm-256color', COLORTERM='truecolor',+ PORT=str(port), TMUX_TMPDIR=str(root / 'tmux'), HN_TMPDIR=str(root / 'hn'),+ HN_SOCKET_NAME='fresh-user', HARNESS_HOMEBREW_PREFIXES=str(root / 'no-homebrew'),+ ANALYTICS_ENABLED='false', HARNESS_DAEMONS='0', HN_DESKTOP='off',+ HARNESS_TUI_NOTIFY='off', ADAPTER_UPDATE_DISABLE='true',+ GIT_TERMINAL_PROMPT='0', CABLE_DISABLE='true', CABLE_FW_DISABLE='true')+ path = root / 'state.json'+ path.write_text(json.dumps(dict(root=str(root), env=env, tmux=tmux), indent=2))+ print(f'State: {path}', flush=True)+ with (root / 'install.log').open('w') as log:+ result = subprocess.run(['/bin/bash', '-o', 'pipefail', '-c',+ 'curl -fsSL https://autonomous.ai/harness.sh | bash'],+ env=env, cwd=home, stdout=log, stderr=subprocess.STDOUT, timeout=600)+ assert result.returncode == 0, (root / 'install.log').read_text()+ # Optional local candidates are applied only after the real public installer completes.+ for variable, destination in [('HN_FRESH_USER_CLI', home / '.harness/cli/cli.js'),+ ('HN_FRESH_USER_BINARY', home / '.harness/bin/harness-tui')]:+ if os.environ.get(variable):+ shutil.copy2(os.environ[variable], destination)+ env['PATH'] = f'{home}/.local/bin:' + env['PATH']+ path.write_text(json.dumps(dict(root=str(root), env=env, tmux=tmux), indent=2))+ user = User(path)+ versions = subprocess.run([str(home / '.local/bin/harness'), 'version'], env=env,+ capture_output=True, text=True, check=True).stdout+ versions += subprocess.run([str(home / '.local/bin/hn'), '--version'], env=env,+ capture_output=True, text=True, check=True).stdout+ (root / 'versions.txt').write_text(versions)+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in env.items()], str(home / '.local/bin/hn')])+ user.outer('-f', '/dev/null', 'new-session', '-d', '-s', 'user', '-x', '130', '-y', '38', command)+ print(versions, flush=True)+ print('Started the real installed hn; use --state for keys, text, screen, snapshot, and stop.', flush=True)+ return user+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--state')+ parser.add_argument('action', choices=['start', 'run', 'screen', 'keys', 'text', 'field', 'wait', 'snapshot', 'status', 'resize', 'stop'])+ parser.add_argument('args', nargs='*')+ args = parser.parse_args()+ user = start() if args.action == 'start' or (args.action == 'run' and not args.state) else User(args.state)+ if args.action == 'run':+ import runpy+ runpy.run_path(str(Path(__file__).with_name('fresh-user-journeys.py')))['run'](user, args.args)+ if args.action == 'screen': print(user.screen(), end='')+ elif args.action == 'keys': user.keys(*args.args)+ elif args.action == 'text': user.text(' '.join(args.args))+ elif args.action == 'field': user.field(' '.join(args.args))+ elif args.action == 'wait': print(user.wait(' '.join(args.args)), end='')+ elif args.action == 'snapshot': user.snapshot(args.args[0])+ elif args.action == 'status': print(json.dumps(user.status(), indent=2))+ elif args.action == 'resize': user.outer('resize-window', '-t', 'user', '-x', args.args[0], '-y', args.args[1])+ elif args.action == 'stop': user.stop()+++if __name__ == '__main__': main()diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.pyindex 9a025fc53..d5816da36 100644--- a/tui/tests/new-harness.py+++ b/tui/tests/new-harness.py@@ -132,6 +132,7 @@ try:*[f'{k}={v}' for k, v in ENV.items()], str(HN), '-L', PREFIX,'--port', str(PORT), '-f', '/dev/null'])tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'test', '-x', '150', '-y', '42', command)+ tmux('set-window-option', '-t', 'test', 'remain-on-exit', 'on')started = Trueshows('Fix flaky login test')first_window = hn('display-message', '-p', '#{window_id}')@@ -215,8 +216,9 @@ try:new_form(); field('Agent'); type_text('claude'); keys('Enter'); field('Options'); choose_field('Approvals', 'plan'); shows('Plan first')keys('Escape'); new_form(); shows('Plan first')count = create_count()- for w, h in [(80, 24), (45, 14), (22, 5), (1, 1), (150, 42)]:+ for w, h in [(80, 24), (45, 14), (22, 5), (1, 1), (150, 42)] * 3:tmux('resize-window', '-t', 'test', '-x', str(w), '-y', str(h)); time.sleep(.4)+ assert tmux('display-message', '-p', '-t', 'test', '#{pane_dead}').strip() == '0', f'hn client exited after resize to {w}x{h}\n' + tmux('capture-pane', '-p', '-S', '-100', '-t', 'test')assert hn('display-message', '-p', '#{window_panes}').isdigit(), 'hn survives tiny resizes'field('Project'); shows('Search projects')tmux('resize-window', '-t', 'test', '-x', '80', '-y', '24')