Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

hn's first run: a command that works, OpenCode with a task typed, one Enter, a new folder (#1130)

Dee8f0f0e5128bd
diff --git a/cli/scripts/install.sh b/cli/scripts/install.sh
index 197148f9e..de40b0a03 100755
--- a/cli/scripts/install.sh
+++ b/cli/scripts/install.sh
@@ -90,6 +90,28 @@ LAUNCHER="$BIN_DIR/harness"
TUI_BIN="$HOME/.harness/bin/harness-tui"
HN_LAUNCHER="$BIN_DIR/hn"
+# The PATH of the terminal this runs in, before the steps below put ~/.local/bin on the installer's
+# own: the closing advice is about the person's PATH. Checked against the installer's, the advice to
+# fix it never printed, and on a fresh Mac the `hn` it said to type was "command not found" (macOS VM,
+# 2026-10-09).
+ORIGINAL_PATH="$PATH"
+
+# A computer with no coding agent and no Harness yet, before this install changes that: hn's first
+# window opens on OpenCode there, so step 4b downloads it, as the desktop app does during its setup
+# (desktop/lib/bootstrap/agent_prefetch.dart `alreadyHasAnAgent`, the same places).
+no_agent_yet() {
+ for path in "$HOME/.harness/cli" "$HOME/.claude" "$HOME/.codex" "$HOME/.opencode/bin/opencode" \
+ "$HOME/.bun/bin/opencode" "$HOME/.config/opencode" "$HOME/.local/share/opencode"; do
+ [ -e "$path" ] && return 1
+ done
+ for name in claude codex opencode; do
+ command -v "$name" >/dev/null 2>&1 && return 1
+ done
+ return 0
+}
+NEW_COMPUTER=0
+if no_agent_yet; then NEW_COMPUTER=1; fi
+
# 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.
@@ -757,6 +779,41 @@ fi
# 4. Ensure ~/.local/bin is on PATH (per shell), idempotently — defined up with the other helpers.
ensure_path_rc
+# 4b. OpenCode, on a computer with no agent at all (NEW_COMPUTER) with a person at the terminal (a
+# Docker build or a provisioning script gets no agent it did not ask for): hn's first window opens
+# on it with a task typed, so it is downloaded now rather than in front of the person in that pane.
+# The CLI's recipe (cli/src/lib/engineInstall.ts) with --no-modify-path, as the desktop app runs
+# it: Harness finds ~/.opencode/bin itself. Never under --desktop, whose app downloads it beside
+# this install. After step 4, so stopping a slow download leaves a working PATH, and never longer
+# than three minutes; optional either way: a pane installs it, with the npm fallback.
+# HARNESS_INSTALL_ATTENDED=1 says a person is there when stdout is not a terminal (the specs).
+if [ "$INSTALL_MODE" = "standalone" ] && [ "$NEW_COMPUTER" = 1 ] \
+ && { [ -t 1 ] || [ "${HARNESS_INSTALL_ATTENDED:-}" = 1 ]; }; then
+ # The mark hn's first start takes (tui/src/first_run.rs): OpenCode with a task typed, not a shell.
+ mkdir -p "$HOME/.harness/tui" && : > "$HOME/.harness/tui/first-run" || true
+ echo "▸ Downloading OpenCode, the free coding agent hn starts with"
+ ( curl -fsSL --connect-timeout 20 https://opencode.ai/install | bash -s -- --no-modify-path ) >/dev/null 2>&1 &
+ download=$!
+ waited=0
+ while kill -0 "$download" 2>/dev/null && [ "$waited" -lt 180 ]; do sleep 1; waited=$((waited + 1)); done
+ kill "$download" 2>/dev/null || true
+ wait "$download" 2>/dev/null || true
+ if [ -x "$HOME/.opencode/bin/opencode" ]; then
+ # Run once, `--version` only, as the desktop does: macOS checks a new binary on its first run
+ # (3.9 s against 0.4 s after, fresh VM, 2026-10-09), which would be hn's first pane's. Never
+ # longer than 20 s.
+ "$HOME/.opencode/bin/opencode" --version >/dev/null 2>&1 &
+ warm=$!
+ ( sleep 20; kill "$warm" 2>/dev/null ) >/dev/null 2>&1 &
+ watchdog=$!
+ wait "$warm" 2>/dev/null || true
+ kill "$watchdog" 2>/dev/null || true
+ echo " ✓ OpenCode ready"
+ else
+ echo " · OpenCode will be installed when hn first starts it"
+ fi
+fi
+
# 5. Final verification. Use the launcher by absolute path because this process cannot update its
# parent shell's PATH. Installation never authenticates or starts the adapter implicitly.
"$NODE_BIN" --version >/dev/null 2>&1 || { echo "✗ Managed Node verification failed." >&2; exit 30; }
@@ -795,7 +852,12 @@ else
echo ""
echo " Start here — every harness on every machine, in this terminal:"
echo ""
- echo " hn # start locally; no login required"
+ # A command that works in THIS terminal: ~/.local/bin is only on new terminals' PATH (step 6).
+ case ":${ORIGINAL_PATH}:" in
+ *":$BIN_DIR:"*) hn_command=hn ;;
+ *) hn_command="~/.local/bin/hn" ;;
+ esac
+ printf ' %-31s# start locally; no login required\n' "$hn_command"
echo ""
echo " Or set this computer up step by step — three commands, in this order:"
echo ""
@@ -816,7 +878,7 @@ fi
# 6. Make `harness` usable by NAME. We already added ~/.local/bin to your rc for NEW terminals (step 4);
# a piped `curl … | sh` can't touch the CURRENT shell's PATH, so print the one line that fixes it here
# now — but ONLY when ~/.local/bin isn't already on PATH (many Linux distros add it), to avoid nagging.
-case ":${PATH}:" in
+case ":${ORIGINAL_PATH}:" in
*":$BIN_DIR:"*) : ;; # already on PATH → `harness` works immediately, nothing to do
*)
echo ""
diff --git a/cli/src/scripts/install.spec.ts b/cli/src/scripts/install.spec.ts
index 619199238..90eea922f 100644
--- a/cli/src/scripts/install.spec.ts
+++ b/cli/src/scripts/install.spec.ts
@@ -142,13 +142,13 @@ const installedFixture = (scratch: string) => {
return { home, node: join(scratch, "node") };
};
-const runFinale = (mode: "standalone" | "desktop", pathHasBin: boolean) => {
+const runFinale = (mode: "standalone" | "desktop", pathHasBin: boolean, script = finaleOf) => {
const source = readFileSync(installer, "utf8");
const scratch = mkdtempSync(join(tmpdir(), "harness-finale-"));
try {
const { home, node } = installedFixture(scratch);
const bin = join(home, ".local", "bin");
- return spawnSync("/bin/sh", ["-c", finaleOf(source)], {
+ return spawnSync("/bin/sh", ["-c", script(source)], {
encoding: "utf8",
env: {
...process.env,
@@ -194,6 +194,23 @@ describe("scripts/install.sh: what it says once it is done", () => {
expect(out.indexOf("harness --help")).toBeLessThan(out.indexOf("'harness' is installed in ~/.local/bin"));
}, 20_000);
+ // The installer puts ~/.local/bin on its own PATH while it runs (the tmux step): the advice is about
+ // the terminal it runs in. Checked against its own, it never printed, and on a fresh Mac the `hn`
+ // it said to type was "command not found" (macOS VM, 2026-10-09).
+ const finaleAfterInstallOf = (source: string) =>
+ source.slice(source.indexOf('METADATA_URL="${HARNESS_METADATA_URL'), source.indexOf("# Shared by every download")) +
+ 'export PATH="$BIN_DIR:$PATH"\n' +
+ source.slice(source.indexOf("# 5. Final verification"));
+
+ it("starts with a command this terminal can run, and says how to get `hn` by name, whatever the install did to its own PATH", () => {
+ const out = runFinale("standalone", false, finaleAfterInstallOf).stdout;
+ expect(out).toMatch(/^ {6}~\/\.local\/bin\/hn +# start locally; no login required$/m);
+ expect(out).toContain("'harness' is installed in ~/.local/bin");
+ const onPath = runFinale("standalone", true, finaleAfterInstallOf).stdout;
+ expect(onPath).toMatch(/^ {6}hn {29}# start locally; no login required$/m);
+ expect(onPath).not.toContain("'harness' is installed in ~/.local/bin");
+ }, 20_000);
+
it("desktop mode gets the one line and no guide: the app takes the person through sign-in", () => {
const out = runFinale("desktop", true).stdout;
expect(out).toContain("harness 0.2.60 installed.");
@@ -896,7 +913,7 @@ describe("scripts/install.sh command contract", () => {
// The helpers plus the grid step alone, as one runnable unit.
const gridStepOf = (source: string) =>
source.slice(source.indexOf('METADATA_URL="${HARNESS_METADATA_URL'), source.indexOf("# 1. Host requirements")) +
- source.slice(source.indexOf("# 3b. The managed grid"), source.indexOf("# 4. Ensure ~/.local/bin"));
+ source.slice(source.indexOf("# 3b. The managed grid"), source.indexOf("# 3c. hn's binary"));
it("installs the managed grid after the CLI and before PATH, as a step the install can survive", () => {
const source = readFileSync(installer, "utf8");
@@ -1261,3 +1278,73 @@ describe("scripts/install.sh: hn", () => {
} finally { rmSync(scratch, { recursive: true, force: true }); }
}, 20_000);
});
+
+describe("scripts/install.sh: OpenCode for hn's first window", () => {
+ // The constants (NEW_COMPUTER among them), then step 3d alone.
+ const openCodeStepOf = (source: string) =>
+ source.slice(source.indexOf('METADATA_URL="${HARNESS_METADATA_URL'), source.indexOf("# Shared by every download")) +
+ source.slice(source.indexOf("# 4b. OpenCode"), source.indexOf("# 5. Final verification"));
+
+ // OpenCode's own installer, as served: a script for bash that puts the binary in ~/.opencode/bin.
+ const run = (mode: string, { agent = "", installs = true, attended = true } = {}) => {
+ const scratch = mkdtempSync(join(tmpdir(), "harness-opencode-"));
+ try {
+ const home = join(scratch, "home");
+ mkdirSync(home, { recursive: true });
+ if (agent) mkdirSync(join(home, agent), { recursive: true });
+ writeCommand(scratch, "curl", [
+ `printf '%s\\n' "$*" >> '${join(scratch, "curl-invocations")}'`,
+ installs
+ ? `printf '%s\\n' 'mkdir -p "$HOME/.opencode/bin"' 'printf "#!/bin/sh\\n" > "$HOME/.opencode/bin/opencode"' 'chmod +x "$HOME/.opencode/bin/opencode"'`
+ : "exit 7",
+ ]);
+ const result = spawnSync("/bin/sh", ["-c", openCodeStepOf(readFileSync(installer, "utf8"))], {
+ encoding: "utf8",
+ env: { ...process.env, HOME: home, INSTALL_MODE: mode, PATH: `${scratch}:/usr/bin:/bin`, HARNESS_INSTALL_ATTENDED: attended ? "1" : "" },
+ });
+ let curl = "";
+ try { curl = readFileSync(join(scratch, "curl-invocations"), "utf8"); } catch { /* never asked */ }
+ const marked = existsSync(join(home, ".harness", "tui", "first-run"));
+ return { result, curl, marked, opencode: join(home, ".opencode", "bin", "opencode") };
+ } finally {
+ rmSync(scratch, { recursive: true, force: true });
+ }
+ };
+
+ it("downloads it on a computer with no agent and no Harness, with the CLI's recipe, into ~/.opencode/bin", () => {
+ const { result, curl, marked } = run("standalone");
+ expect(result.status).toBe(0);
+ expect(curl).toContain("https://opencode.ai/install");
+ expect(marked, "hn's first start opens OpenCode (tui/src/first_run.rs)").toBe(true);
+ expect(result.stdout).toContain("✓ OpenCode ready");
+ const source = readFileSync(installer, "utf8");
+ const step = source.indexOf("# 4b. OpenCode");
+ expect(source.slice(step, source.indexOf("# 5. Final verification"))).toContain("bash -s -- --no-modify-path");
+ // After ~/.local/bin is on PATH: stopping a slow download leaves a working PATH.
+ expect(step).toBeGreaterThan(source.indexOf("\nensure_path_rc\n"));
+ }, 20_000);
+
+ it("leaves it alone where there is an agent or Harness already, and to the app under --desktop", () => {
+ for (const agent of [".claude", ".codex", ".harness/cli", ".config/opencode"]) {
+ const { result, curl, marked } = run("standalone", { agent });
+ expect(result.status, agent).toBe(0);
+ expect(curl, agent).toBe("");
+ expect(marked, agent).toBe(false);
+ }
+ for (const mode of ["desktop", "host"]) {
+ const { curl, marked } = run(mode);
+ expect(curl, mode).toBe("");
+ expect(marked, mode).toBe(false);
+ }
+ // Nobody at a terminal (a Docker build, a provisioning script): no agent it did not ask for.
+ const unattended = run("standalone", { attended: false });
+ expect(unattended.curl).toBe("");
+ expect(unattended.marked).toBe(false);
+ }, 20_000);
+
+ it("survives a download that fails: says a pane will install it, and the install goes on", () => {
+ const { result } = run("standalone", { installs: false });
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain("OpenCode will be installed when hn first starts it");
+ }, 20_000);
+});
diff --git a/tui/src/app.rs b/tui/src/app.rs
index 3c507c98b..0d34516d1 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -713,6 +713,8 @@ pub struct App {
/// A disposable USB session offers direct try, install and network actions on its home.
pub os_live: bool,
pub os_welcome: crate::os_welcome::State,
+ /// A computer's first hn opening OpenCode with a task typed (first_run.rs).
+ pub first_run: crate::first_run::State,
pub os_first_use: bool,
/// While a command runs in another session (`-t work:2`): the session to come back to.
pub swap_back: Option<u32>,
@@ -941,6 +943,7 @@ impl App {
os_session: std::env::var("HARNESS_OS").as_deref() == Ok("1"),
os_live: std::env::var("HARNESS_OS").as_deref() == Ok("1") && std::env::var("HARNESS_OS_LIVE").as_deref() == Ok("1"),
os_welcome: Default::default(),
+ first_run: Default::default(),
os_first_use: std::env::var("HARNESS_OS_FIRST_USE").as_deref() == Ok("1"),
wait_channels: HashMap::new(),
cli_held: std::collections::VecDeque::new(),
@@ -5753,6 +5756,13 @@ impl App {
if !(self.tabs.len() == 1 && self.tabs[0].root.is_none()) { self.shell_asked = true; return }
if self.link(&self.fleet.local_id).is_none() { return }
self.shell_asked = true;
+ // A computer's first hn, as the installer marked it: OpenCode with a task typed, not a shell
+ // (first_run.rs). Only a plain `hn`: `hn new`, its folder, its command and a chain after it
+ // are asked for, and get them.
+ if self.start_session.is_none() && self.start_then.is_empty() && crate::first_run::take() {
+ crate::first_run::start(self);
+ return;
+ }
// The desk's first shell: where hn was started (-c: where it was asked to), running what
// `hn new` asked for.
let start = self.start_session.take().unwrap_or_default();
@@ -6329,6 +6339,7 @@ impl App {
pub fn on_tick(&mut self) {
crate::os_welcome::tick(self);
+ crate::first_run::tick(self);
self.run_start_then();
crate::new_harness::welcome_tick(self);
self.ask_said();
diff --git a/tui/src/first_run.rs b/tui/src/first_run.rs
new file mode 100644
index 000000000..6318364ed
--- /dev/null
+++ b/tui/src/first_run.rs
@@ -0,0 +1,137 @@
+//! A computer's first `hn`: OpenCode in a new project with a first task typed in, where tmux, and hn on
+//! every later start, opens a shell. It is the desktop app's first workspace for someone with no coding
+//! agent (desktop/lib/state/first_arrival.dart), in a terminal: a fresh Mac's first `hn` was a shell
+//! prompt with nothing saying what to do next, and its first harness wrote its files straight into the
+//! home folder (macOS VM, 2026-10-09).
+//!
+//! Only where the installer found no agent and no Harness, with a person at the terminal
+//! (cli/scripts/install.sh, step 4b): it downloads OpenCode and leaves the mark [take] removes, so
+//! this happens once, on a plain `hn` started where the installer ran, the home folder, within a day.
+//! Nothing is sent: the task is typed into OpenCode's box and waits for the person's Return.
+use std::path::Path;
+use std::time::{Duration, Instant, SystemTime};
+use crate::app::{App, Placement};
+
+/// What the desktop app types for someone with no agent (`FirstArrival.starterTask`).
+pub const STARTER_TASK: &str = "make a small web page that shows today's date";
+/// How long OpenCode may take to show its box: its first start on a fresh computer, or its install in
+/// the pane when the installer's download did not finish.
+const WAIT: Duration = Duration::from_secs(180);
+/// A moment for the box to take focus after it is first drawn, as the desktop waits.
+const SETTLE: Duration = Duration::from_millis(800);
+/// A mark older than this is not a first run any more: the person has had the computer, and maybe
+/// other agents, since the install.
+const FRESH: Duration = Duration::from_secs(24 * 60 * 60);
+
+#[derive(Default)]
+pub struct State {
+ since: Option<Instant>,
+ /// The harness this made, from its creation reply: the one pane the task goes to.
+ agent: Option<(String, String)>,
+ ready_at: Option<Instant>,
+}
+
+/// The installer's mark (cli/scripts/install.sh step 4b).
+pub fn mark() -> std::path::PathBuf { crate::app::state_dir().join("first-run") }
+
+/// The installer's mark, taken: true once, when hn was started in the home folder (where the installer
+/// ran and its "Start here" was typed) and the mark is fresh. Started anywhere else, hn opens its shell
+/// there and the mark waits; a stale one is removed.
+pub fn take() -> bool {
+ let home = std::env::var("HOME").unwrap_or_default();
+ let here = std::env::current_dir().unwrap_or_default();
+ take_at(&mark(), &here, Path::new(&home), SystemTime::now())
+}
+
+fn take_at(mark: &Path, here: &Path, home: &Path, now: SystemTime) -> bool {
+ let Ok(meta) = std::fs::metadata(mark) else { return false };
+ let age = meta.modified().ok().and_then(|at| now.duration_since(at).ok()).unwrap_or_default();
+ if age > FRESH {
+ let _ = std::fs::remove_file(mark);
+ return false;
+ }
+ if home.as_os_str().is_empty() || here != home { return false }
+ std::fs::remove_file(mark).is_ok()
+}
+
+/// OpenCode on this computer, in a new project the daemon makes and names, with nothing sent.
+pub fn start(app: &mut App) {
+ let machine = app.fleet.local_id.clone();
+ let what = crate::modal::What { engine: "opencode".into(), dsh: None, label: crate::theme::engine_label("opencode").into() };
+ app.first_run = State { since: Some(Instant::now()), ..State::default() };
+ let opts = crate::input::NewOpts { first_run: true, ..Default::default() };
+ crate::input::create_opts(app, machine, what, None, None, false, opts);
+}
+
+/// The creation reply: the harness the task is typed into.
+pub fn created(app: &mut App, machine: &str, agent: &str) {
+ if app.first_run.since.is_some() { app.first_run.agent = Some((machine.into(), agent.into())) }
+}
+
+/// Nothing was made: the shell this window would have had, where hn was started, unless the person has
+/// opened something meanwhile.
+pub fn failed(app: &mut App) {
+ app.first_run = State::default();
+ if app.tab().root.is_some() { return }
+ let cwd = std::env::current_dir().ok().map(|d| d.display().to_string());
+ crate::input::new_shell_from(app, None, Placement::Auto(None), cwd, None);
+}
+
+/// Types the task into the harness this made once OpenCode shows its box there, a moment after it is
+/// first seen. Nowhere else: not another OpenCode the person opened meanwhile, not a shell the pane
+/// fell back to.
+pub fn tick(app: &mut App) {
+ let Some(since) = app.first_run.since else { return };
+ if since.elapsed() > WAIT {
+ app.first_run = State::default();
+ return;
+ }
+ let Some((machine, agent)) = app.first_run.agent.clone() else { return };
+ let Some((_, pane)) = app.find_pane(&machine, &agent) else { return };
+ let opencode = app.fleet.agent(&machine, &agent).is_some_and(|a| a.engine == "opencode");
+ if !opencode || !app.panes.get(&pane).is_some_and(|p| opencode_ready(&p.text_range(None, None))) {
+ app.first_run.ready_at = None;
+ return;
+ }
+ if app.first_run.ready_at.get_or_insert_with(Instant::now).elapsed() < SETTLE { return }
+ app.send_input(pane, STARTER_TASK.as_bytes());
+ app.first_run = State::default();
+}
+
+/// OpenCode's home screen: the key hints under its box or its placeholder, phrases only OpenCode
+/// prints, so a shell or an install in progress never passes (desktop `FirstArrival.openCodeReady`).
+pub fn opencode_ready(screen: &str) -> bool {
+ let text = screen.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ");
+ text.contains("ctrl+p commands") || text.contains("ask anything")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn opencodes_box_is_known_by_its_own_words_only() {
+ assert!(opencode_ready(" ┃ make a page\n Build auto · Muse Spark 1.3\n tab agents ctrl+p commands"));
+ assert!(opencode_ready("> Ask anything... \"Fix a TODO in the codebase\""));
+ assert!(!opencode_ready("admin@mac ~ % "));
+ assert!(!opencode_ready("Installing OpenCode… almost there"));
+ }
+
+ #[test]
+ fn the_mark_is_taken_once_from_home_while_fresh() {
+ let dir = std::env::temp_dir().join(format!("hn-first-run-{}", std::process::id()));
+ let home = dir.join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ let mark = dir.join("first-run");
+ let now = SystemTime::now();
+ std::fs::write(&mark, "").unwrap();
+ assert!(!take_at(&mark, &home.join("project"), &home, now), "started elsewhere: its shell there");
+ assert!(mark.exists(), "the mark waits for a start at home");
+ assert!(take_at(&mark, &home, &home, now));
+ assert!(!take_at(&mark, &home, &home, now), "a second start is an ordinary one");
+ std::fs::write(&mark, "").unwrap();
+ assert!(!take_at(&mark, &home, &home, now + FRESH + Duration::from_secs(60)));
+ assert!(!mark.exists(), "a stale mark is removed");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/tui/src/input.rs b/tui/src/input.rs
index 93f03b24c..d07632561 100644
--- a/tui/src/input.rs
+++ b/tui/src/input.rs
@@ -1610,6 +1610,7 @@ fn creation_finished(app: &mut App, machine: String, session: u32, opts: NewOpts
Ok(reply) => {
if let Some(id) = reply.pointer("/agent/id").and_then(|v| v.as_str()) {
if let Some(form_id) = &opts.form_id { crate::new_harness::created(app, form_id, &reply["agent"]); }
+ if opts.first_run { crate::first_run::created(app, &machine, id) }
app.fleet.agents.insert((machine.clone(), id.to_string()), crate::fleet::agent_from(&machine, &reply["agent"], None));
if reply["agent"]["engine"] == "terminal" { app.shells.insert((machine.clone(), id.to_string())); }
// Keep new harnesses in the current window, filling it or splitting beside
@@ -1645,12 +1646,14 @@ fn creation_finished(app: &mut App, machine: String, session: u32, opts: NewOpts
} else {
if let Some(tx) = app.held_reply.take().filter(|_| opts.print.is_some()) { app.print_new = None; let _ = tx.send((Vec::new(), vec!["the machine created no harness".into()], 1)); return }
if let Some(form_id) = &opts.form_id { crate::new_harness::completed(app, form_id, Some("The machine created no harness — try again".into())); }
+ if opts.first_run { crate::first_run::failed(app) }
app.say("The machine created no harness", theme::DANGER)
}
}
Err(e) => {
if let Some(tx) = app.held_reply.take().filter(|_| opts.print.is_some()) { app.print_new = None; let _ = tx.send((Vec::new(), vec![format!("create harness failed: {e}")], 1)); return }
if let Some(form_id) = &opts.form_id { crate::new_harness::completed(app, form_id, Some(format!("Could not start it: {e}"))); }
+ if opts.first_run { crate::first_run::failed(app) }
app.say(format!("Could not start it: {e}"), theme::DANGER)
}
}
@@ -3523,6 +3526,8 @@ pub struct NewOpts {
/// Additional project/permission choices from the interactive draft.
pub extra: Option<serde_json::Value>, pub form_id: Option<String>,
pub target: Option<LaunchTarget>,
+ /// A computer's first hn (first_run.rs): told what was made, or that nothing was.
+ pub first_run: bool,
}
#[derive(Clone, Debug)]
diff --git a/tui/src/main.rs b/tui/src/main.rs
index c5c3be2da..51a948cf1 100644
--- a/tui/src/main.rs
+++ b/tui/src/main.rs
@@ -56,6 +56,7 @@ mod new_harness;
mod mouse;
mod options;
mod os_welcome;
+mod first_run;
mod paste;
mod pane;
mod pane_frame;
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
index 9008646cb..4c8cf27c9 100644
--- a/tui/src/new_harness.rs
+++ b/tui/src/new_harness.rs
@@ -344,6 +344,13 @@ fn short_path(path: &str, home: &str) -> String {
path.into()
}
}
+/// A machine's home folder: as its daemon reported it, or this computer's own.
+fn machine_home(app: &App, machine: &str) -> Option<String> {
+ app.homes.get(machine).cloned().or_else(|| {
+ (machine == app.fleet.local_id || crate::local::is_local(machine)).then(|| std::env::var("HOME").ok()).flatten()
+ })
+}
+
fn machine_label(app: &App, machine: &str) -> String {
if app.fleet.machines.iter().any(|m| m.id == machine && m.local) {
"local".into()
@@ -495,11 +502,20 @@ fn make_form(app: &mut App, machine: Option<String>, cwd: Option<String>, surfac
.and_then(|p| app.fleet.agent(&p.machine_id, &p.agent_id));
let what = saved_agent(&saved);
let engine = what.engine.clone();
- let project = cwd
- .or_else(|| saved["projects"][&machine].as_str().map(str::to_string))
- .or_else(|| current.map(|a| a.cwd.clone()).filter(|p| !p.is_empty()))
- .map(Project::Folder)
- .unwrap_or_else(|| Project::New(String::new()));
+ // The home folder is nobody's project: hn's first shell starts there, and a fresh Mac's first
+ // harness, from that shell, wrote its files straight into it (macOS VM, 2026-10-09). Where the form
+ // was opened from home, a new project, as the desktop app makes one. A project the person chose
+ // (remembered) stays theirs, and a terminal from it opens at home (set_engine, the welcome row).
+ let home = machine_home(app, &machine);
+ let at_home = |p: &String| home.as_deref().is_some_and(|h| p.trim_end_matches('/') == h.trim_end_matches('/'));
+ let project = if cwd.as_ref().is_some_and(at_home) {
+ Project::New(String::new())
+ } else {
+ cwd.or_else(|| saved["projects"][&machine].as_str().map(str::to_string))
+ .or_else(|| current.map(|a| a.cwd.clone()).filter(|p| !p.is_empty() && !at_home(p)))
+ .map(Project::Folder)
+ .unwrap_or_else(|| Project::New(String::new()))
+ };
let permission = saved["permissions"][&engine]
.as_str()
.map(str::to_string)
@@ -571,11 +587,7 @@ fn refresh_form(app: &App, form: &mut Form) {
form.child_active = false;
form.trail.clear();
}
- form.home = app
- .homes
- .get(&form.draft.machine)
- .cloned()
- .unwrap_or_default();
+ form.home = machine_home(app, &form.draft.machine).unwrap_or_default();
if form.draft.what.engine == "terminal"
&& matches!(&form.draft.project,Project::Folder(p) if p.is_empty())
&& !form.home.is_empty()
@@ -1487,6 +1499,9 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
KeyCode::Enter if !key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT) => {
form.focus = Field::Create;
form.child = None;
+ // With a task, Enter starts it: the second Enter, on Start, was the step a newcomer
+ // stopped at (macOS VM, 2026-10-09). Without one it still steps to Start.
+ launch = !form.draft.task.trim().is_empty();
}
_ if form.blocked(Field::Task).is_none() => {
form.task_editor.key(&mut form.draft.task, key, form.task_area.width.max(1) as usize);
@@ -2334,6 +2349,37 @@ mod tests {
assert_eq!(form.focus, Field::Task);
}
+ // The second Enter, on Start, was where a newcomer stopped (macOS VM, 2026-10-09).
+ #[tokio::test]
+ async fn enter_in_a_task_starts_it_and_an_empty_task_steps_to_start() {
+ let mut app = app();
+ let mut form = make_form(&mut app, Some(crate::local::MACHINE.into()), Some("/home/dev/project".into()), Surface::Dialog).unwrap();
+ key(&mut app, form, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ form = take_active(&mut app).unwrap();
+ assert_eq!(form.focus, Field::Create, "no task: Enter steps to Start");
+ assert!(form.attempt.is_none() && !form.starting);
+ form.focus = Field::Task;
+ form.draft.task = "make a small web page".into();
+ key(&mut app, form, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ let form = take_active(&mut app).unwrap();
+ assert!(form.attempt.is_some() || form.starting || !form.error.is_empty(), "the task was submitted");
+ }
+
+ // The home folder is nobody's project: a fresh Mac's first harness wrote into it.
+ #[tokio::test]
+ async fn the_home_folder_is_a_new_project_unless_the_harness_is_a_terminal() {
+ let mut app = app();
+ let home = std::env::var("HOME").unwrap();
+ app.homes.insert(crate::local::MACHINE.into(), home.clone());
+ let form = make_form(&mut app, Some(crate::local::MACHINE.into()), Some(format!("{home}/")), Surface::Dialog).unwrap();
+ assert!(matches!(&form.draft.project, Project::New(name) if name.is_empty()), "{:?}", form.draft.project);
+ let form = make_form(&mut app, Some(crate::local::MACHINE.into()), Some(format!("{home}/work")), Surface::Dialog).unwrap();
+ assert!(matches!(&form.draft.project, Project::Folder(path) if path.ends_with("/work")));
+ let mut form = make_form(&mut app, Some(crate::local::MACHINE.into()), Some(home.clone()), Surface::Dialog).unwrap();
+ set_engine(&mut form, "terminal");
+ assert!(matches!(&form.draft.project, Project::Folder(path) if *path == home), "a shell still opens at home");
+ }
+
#[tokio::test]
async fn offline_submission_explains_recovery_and_preserves_the_task_on_both_surfaces() {
for window in [false, true] {
@@ -2345,10 +2391,7 @@ mod tests {
let mut form = make_form(&mut app, Some(crate::local::MACHINE.into()), Some("/home/dev/project".into()), surface).unwrap();
assert!(form.local_only);
form.draft.task = "Keep my offline task".into();
- key(&mut app, form, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
- let form = take_active(&mut app).unwrap();
- assert_eq!(form.focus, Field::Create);
- assert!(form.error.is_empty());
+ // One Enter with a task submits it, and says why it could not start.
key(&mut app, form, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
let form = take_active(&mut app).unwrap();
assert!(form.error.contains("harness start"));
diff --git a/tui/src/new_harness/welcome.rs b/tui/src/new_harness/welcome.rs
index 7fdfaed3f..ee57e697c 100644
--- a/tui/src/new_harness/welcome.rs
+++ b/tui/src/new_harness/welcome.rs
@@ -148,13 +148,17 @@ pub(super) fn activate(app: &mut App, mut form: Box<Form>) {
crate::commands::execute(app, "choose-tree -Zs");
}
Field::Terminal => {
- // This action opens the selected folder without sending the task to a shell.
- let Project::Folder(cwd) = &form.draft.project else {
- form.error = "Choose an existing project folder for a terminal.".into();
- store_form(app, form);
- return;
+ // This action opens the selected folder without sending the task to a shell; a new project
+ // has none yet, so the shell opens at home, where the form was opened from.
+ let cwd = match &form.draft.project {
+ Project::Folder(cwd) => cwd.clone(),
+ Project::New(_) if !form.home.is_empty() => form.home.clone(),
+ _ => {
+ form.error = "Choose an existing project folder for a terminal.".into();
+ store_form(app, form);
+ return;
+ }
};
- let cwd = cwd.clone();
let machine = crate::input::shell_machine(app, Some(&(form.draft.machine.clone(), String::new())));
let backing = app.focused().and_then(|p| app.panes.get(&p)).is_some_and(|p| {
app.fleet.agent(&p.machine_id, &p.agent_id).is_some_and(|a|
@@ -434,9 +438,7 @@ mod tests {
assert!(matches!(&app.welcome.forms[&tab].draft.project,
Project::Folder(path) if path == "/srv/remote-project"));
crate::input::handle(&mut app, crossterm::event::Event::Paste("keep this remote task".into()));
- event(&mut app, KeyCode::Enter, KeyModifiers::NONE);
- assert_eq!(app.welcome.forms[&tab].focus, Field::Create);
- assert!(app.welcome.forms[&tab].error.is_empty(), "task Enter only selects Start");
+ // One Enter with a task submits it.
event(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let form = &app.welcome.forms[&tab];
assert_eq!(form.draft.machine, "remote");
@@ -449,6 +451,22 @@ mod tests {
}
}
+ // A window opened from home gets a new project for its harness; its terminal still opens at home.
+ #[tokio::test]
+ async fn a_terminal_from_a_window_opened_at_home_opens_at_home() {
+ let mut app = app();
+ let home = std::env::var("HOME").unwrap();
+ app.homes.insert(crate::local::MACHINE.into(), home.clone());
+ ensure(&mut app, None, Some(home.clone()));
+ let tab = app.tab().id.clone();
+ assert!(matches!(&app.welcome.forms[&tab].draft.project, Project::New(_)));
+ let mut form = take_active(&mut app).unwrap();
+ form.focus = Field::Terminal;
+ activate(&mut app, form);
+ let error = app.welcome.forms.get(&tab).map(|f| f.error.clone()).unwrap_or_default();
+ assert!(!error.contains("existing project folder"), "{error}");
+ }
+
#[tokio::test]
async fn task_arrows_leave_at_visual_edges_and_keep_multiline_editing_inside() {
let mut app = app();
@@ -484,8 +502,6 @@ mod tests {
store_form(&mut app, form);
render(&mut app);
event(&mut app, KeyCode::Enter, KeyModifiers::NONE);
- assert_eq!(app.welcome.forms[&tab].focus, Field::Create);
- event(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.welcome.forms[&tab].error.contains("cannot start with a task"));
event(&mut app, KeyCode::Esc, KeyModifiers::NONE);
assert_eq!(app.welcome.forms[&tab].focus, Field::Agent);