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.

fix(release): preserve hn window ownership and publish the installer

Dee610eb9893130
diff --git a/.github/workflows/release-tui.yml b/.github/workflows/release-tui.yml
index 0cd6aec5b..c73f9b2d3 100644
--- a/.github/workflows/release-tui.yml
+++ b/.github/workflows/release-tui.yml
@@ -45,6 +45,8 @@ jobs:
(cd cli && npm ci --no-audit --no-fund)
(cd tui && cargo build --locked --release)
tui/tests/e2e.sh
+ - name: Native terminal lifecycle and concurrent window creation
+ run: python3 -u tui/tests/native-terminal.py
build:
needs: test
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 69a33e5c2..d43d5ff6d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -263,6 +263,18 @@ jobs:
echo "Running daemons self-update within ~1 min."
} >> "$GITHUB_STEP_SUMMARY"
+ # Fresh installs need the launchers and runtime setup from this same release.
+ # Scratch manifests must not replace the production installer.
+ - name: Publish and verify the CLI installer
+ if: needs.version.outputs.metadata_path == 'harness/cli/metadata.json'
+ run: |
+ set -euo pipefail
+ bash cli/scripts/upload-install-sh.sh
+ curl -fsSL --retry 3 --retry-all-errors --max-time 30 \
+ https://cdn.autonomous.ai/harness/cli/install.sh \
+ -o "$RUNNER_TEMP/cli-install.sh"
+ cmp cli/scripts/install.sh "$RUNNER_TEMP/cli-install.sh"
+
# The GitHub Release. Notes are the tag's OWN message, verbatim — the same rule the desktop repo
# follows. CI generates nothing: what a human wrote and reviewed at tag time is exactly what
# publishes, and `generate_release_notes` would append a second, differently-built list under it
diff --git a/cli/RELEASE.md b/cli/RELEASE.md
index c3c700feb..10b9624a8 100644
--- a/cli/RELEASE.md
+++ b/cli/RELEASE.md
@@ -56,9 +56,11 @@ A failed build stops the release; nothing is uploaded and no version is consumed
## The `curl | bash` installer
`cli/scripts/install.sh` is what `curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | bash`
-runs: it installs the managed Node runtime and the CLI bundle from the same manifests the release
-publishes to. It is a static file, versioned by nothing, and does **not** ship with a release — publish
-it on its own whenever it changes:
+runs: it installs the managed Node runtime, CLI bundle and hn from their published manifests.
+After verifying a production CLI release, `release.yml` publishes this installer from the same
+commit and checks that the CDN serves the exact source bytes. Releases to a scratch manifest leave
+the production installer alone. The installer is a static, unversioned file; a maintainer can also
+publish an installer-only correction:
```bash
make upload-cli-install-sh # cli/scripts/install.sh -> harness/cli/install.sh in the bucket
diff --git a/docs/research/2026-09-28-hn-release-race.md b/docs/research/2026-09-28-hn-release-race.md
new file mode 100644
index 000000000..8549da7ef
--- /dev/null
+++ b/docs/research/2026-09-28-hn-release-race.md
@@ -0,0 +1,58 @@
+# hn release candidate: concurrent window creation
+
+A fresh check of the merged hn source found a real asynchronous creation race.
+[CI run 36384795117](https://github.com/autonomous-ai/openharness/actions/runs/36384795117)
+failed on Linux x86-64 because window 18 contained `FAST_19`.
+The corresponding [0.1.0 release run](https://github.com/autonomous-ai/openharness/actions/runs/36384791426)
+was cancelled before its publish job ran. Its tag remains a record of that
+unpublished candidate; the corrected candidate is 0.1.1.
+
+## Cause and correction
+
+`new-window` reserved a tab but placed its eventual shell in the active tab when
+the asynchronous response arrived. Standalone CLI commands did not wait for that
+response. Concurrent requests also shared a print format, reply slot, detached
+selection restoration and last-created hook target.
+
+The correction anchors placement to the reserved window ID and restores detached
+selection before yielding. Each command waits only for the shell it started and
+receives that request's output, error and exact session/window/pane identity.
+After-hooks retain that identity through their own asynchronous commands.
+Background shells open their streams, initial geometry survives placement, and
+killed targets delete newly created shells. Cancelled command replies fail rather
+than becoming empty successes. Popups retain their separate lifecycle.
+
+The TUI release workflow now runs the native terminal integration before building
+and publishing. The CLI release workflow separately publishes and byte-verifies
+the current installer only after a production bundle passes its download checks.
+
+## Deterministic regression
+
+`async_creation()` in `tui/tests/native-terminal.py` pauses only its private local
+supervisor, then overlaps one plain and two printed detached window requests.
+It checks that unrelated reads still finish, creation replies remain pending,
+commands and output reach the intended windows, and a later selection is never
+replaced by an older completion. Two further requests exercise delayed
+`after-new-window` hooks. Killing a reserved target must fail its caller and leave
+no supervisor child behind.
+
+The original frozen build fails this case. An independent tmux reviewer verified
+the corrected frozen build against real tmux 3.5a and found no blocker. The final
+macOS binary has SHA-256
+`f27733e1bef6136ae63a1812bce65000ced42feddb83f8489b8298180664ddc5`.
+
+Local verification passed:
+
+- 122 release unit tests.
+- Full mock-daemon E2E and local-shell lifecycle, including exact 176 KB paste,
+ detach/crash recovery and daemon loss/reconnection.
+- Full native terminal comparisons: concurrent creation, cancelled-target cleanup,
+ retained exits/signals, hooks, respawn, startup typeahead and 1-by-1 geometry.
+- All four native and rendered terminal-attribute comparisons.
+- Release workflow YAML and installer shell syntax checks.
+
+These tests use frozen copies, disposable homes, guarded ports, explicit hn and
+tmux sockets, and cleanup of their own processes. They do not use a real daemon,
+real harnesses, default servers or the installed hn. The creature remains outside
+the TUI. Linux CI and publication are separate gates recorded on the release PR
+and workflow runs; this document records the correction and local evidence.
diff --git a/tui/Cargo.lock b/tui/Cargo.lock
index cbf17ba48..2bb2bcae8 100644
--- a/tui/Cargo.lock
+++ b/tui/Cargo.lock
@@ -619,7 +619,7 @@ dependencies = [
[[package]]
name = "harness-tui"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"alacritty_terminal",
"crossterm",
diff --git a/tui/Cargo.toml b/tui/Cargo.toml
index 2745eec63..90680a75a 100644
--- a/tui/Cargo.toml
+++ b/tui/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "harness-tui"
-version = "0.1.0"
+version = "0.1.1"
edition = "2024"
[dependencies]
diff --git a/tui/src/app.rs b/tui/src/app.rs
index fb54feb4c..22f2ea64f 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -202,6 +202,9 @@ pub type Reply = (Vec<String>, Vec<String>, i32);
/// Type-ahead belongs to the shell request that will receive it, even if another starts first.
pub type ShellInput = std::sync::Arc<std::sync::Mutex<Vec<Vec<u8>>>>;
+/// One shell request's printed output and exact session/window/pane, or its error.
+pub type ShellCompletion = Result<(Vec<String>, (u32, String, u64)), String>;
+
/// A Claude Code or Codex conversation on a machine that Harness did not start (a session_search
/// hit with `external`): offered on the home page and found by C-b s, and resumed as a harness.
#[derive(Clone, Debug)]
@@ -473,9 +476,6 @@ pub struct App {
pub home_moved: bool,
/// More commands of the same line or binding wait behind the one running.
pub chain_follows: bool,
- /// The window and pane a shell was last made in (new-window's, split-window's): what their
- /// after- hooks are about.
- pub last_made: Option<(String, u64)>,
/// The Claude Code and Codex conversations Harness did not start that the home page offers
/// (each machine's session index, asked once each time the page shows), and the machines
/// asked so far.
@@ -663,8 +663,6 @@ pub struct App {
/// select-pane -m: the marked pane (join-pane and swap-pane take it as their source).
pub marked: Option<u64>,
pub marked_session: Option<u32>,
- /// new-window -d: the window to go back to (and the last window then) once its shell is up.
- pub return_to: Option<(String, Vec<String>)>,
pub held_reply: Option<tokio::sync::oneshot::Sender<Reply>>,
/// A command that waits for what it opened (display-menu; command-prompt and confirm-before
/// without -b): the shell that ran it is answered when that closes (CMD_RETURN_WAIT).
@@ -747,7 +745,7 @@ pub struct App {
pub shell_inputs: HashMap<String, ShellInput>,
/// Commands waiting for a shell on its way to have its pane (a chain after new-session,
/// new-window, split-window): told when it has come (or failed).
- pub shell_waiters: Vec<(ShellInput, tokio::sync::oneshot::Sender<()>)>,
+ pub shell_waiters: Vec<(ShellInput, tokio::sync::oneshot::Sender<ShellCompletion>)>,
/// `hn new … \; cmd …` / `hn attach … \; cmd …`: the chain after the command that started this
/// client, run once its session is there (and its first shell, for new).
pub start_then: Vec<String>,
@@ -856,7 +854,6 @@ impl App {
back_from: None,
marked: None,
marked_session: None,
- return_to: None,
held_reply: None,
wait_cli: false,
waiting_reply: None,
@@ -924,7 +921,6 @@ impl App {
home_cursor: 0,
home_moved: false,
chain_follows: false,
- last_made: None,
home_external: Vec::new(),
home_asked: HashSet::new(),
home_shown: false,
@@ -1833,7 +1829,7 @@ impl App {
// (A window not in front is as big as it was when last in front, or made.)
let front = self.swap_back.is_none_or(|b| b == self.session_id) && self.tabs.get(self.active).map(|t| t.id == tab.id).unwrap_or(false);
let manual = self.options.get("window-size", &tab.id, None).as_deref() == Some("manual");
- let creating = front && self.return_to.is_some() && tab.size.is_some();
+ let creating = self.shell_inputs.contains_key(&tab.id) && tab.size.is_some();
if !self.headless && self.swap_back.is_none_or(|b| b == self.session_id) && !manual && !creating && (front || tab.root.is_none()) { return self.body() }
let (w, h) = tab.root.as_ref().map(|r| r.size()).unwrap_or_else(|| tab.size.unwrap_or(self.default_size()));
Rect::new(0, if front && !self.headless { self.body().y } else { 0 }, w, h)
@@ -1896,7 +1892,7 @@ impl App {
for i in 0..self.tabs.len() {
let status = self.pane_status(&self.tabs[i]);
let manual = self.options.get("window-size", &self.tabs[i].id, None).as_deref() == Some("manual");
- let creating = self.tabs[i].root.is_none() || (i == self.active && self.return_to.is_some());
+ let creating = self.tabs[i].root.is_none() || self.shell_inputs.contains_key(&self.tabs[i].id);
let size = if manual { self.tabs[i].size.or_else(|| self.tabs[i].root.as_ref().map(|r| r.size())) }
else if creating && self.tabs[i].size.is_some() { self.tabs[i].size }
else { self.tabs[i].size = None; (onscreen && i == self.active).then_some((body.width, body.height)) };
@@ -3826,7 +3822,9 @@ impl App {
Some(t) if t.root.is_none() => { let (w, h) = t.size.unwrap_or((w, h)); t.root = Some(Node::new(id, w, h)); t.focus = Some(id) }
_ => { self.end_shell(id); self.drop_pane(id); return }
}
- if here == Some(self.active) { self.open_stream(id, true) }
+ // A newly created shell must start even if its window is now in the background.
+ self.open_stream(id, true);
+ if let Some(index) = here.filter(|i| !self.tabs[*i].first_named) { self.name_tab_after_first_at(index) }
self.fit_panes();
if here.is_some() && self.session_desk { self.desk_pane_added(tab_id, machine_id, agent_id) }
self.save_sessions();
@@ -3857,8 +3855,8 @@ impl App {
}
let id = self.new_pane(machine_id, agent_id);
if let Placement::At(at) = &placement {
- let Some(t) = self.tabs.iter().position(|x| x.id == at.tab) else { self.drop_pane(id); return };
- if !self.split_at(t, id, at) { self.drop_pane(id); self.error("no space for new pane"); return }
+ let Some(t) = self.tabs.iter().position(|x| x.id == at.tab) else { self.end_shell(id); self.drop_pane(id); return };
+ if !self.split_at(t, id, at) { self.end_shell(id); self.drop_pane(id); self.error("no space for new pane"); return }
let tab = &mut self.tabs[t];
tab.add_pane(id, at.pane, at.before, at.full);
// The new shell's first output is the window's activity (its time, not an alert).
@@ -4159,12 +4157,14 @@ impl App {
if rect.width as f32 >= rect.height as f32 * 2.2 { Dir::Horizontal } else { Dir::Vertical }
}
- fn name_tab_after_first(&mut self) {
- let tab = &self.tabs[self.active];
+ fn name_tab_after_first(&mut self) { self.name_tab_after_first_at(self.active) }
+
+ fn name_tab_after_first_at(&mut self, index: usize) {
+ let tab = &self.tabs[index];
if tab.named || tab.home { return }
let Some(first) = tab.panes().first().copied() else { return };
let name = self.panes.get(&first).and_then(|p| self.fleet.agent(&p.machine_id, &p.agent_id)).map(|a| a.name.clone());
- if let Some(name) = name { self.tabs[self.active].name = name }
+ if let Some(name) = name { self.tabs[index].name = name }
}
pub fn sync_titles(&mut self) {
@@ -4688,9 +4688,6 @@ impl App {
if let Some(found) = self.mouse_ev.as_ref().filter(|m| m.valid).and_then(|m| crate::mouse::mouse_pane(self, m)) { return Some(found) }
// A hook's commands: the pane (window) it is about — for a command's that made one, the
// one it made.
- if let Some((tab, pane)) = self.hook_state.as_ref().filter(|h| h.made).and(self.last_made.clone()) {
- if let Some(w) = self.tabs.iter().position(|t| t.id == tab) { return Some((w, pane)) }
- }
if let Some((tab, pane)) = self.hook_state.as_ref().and_then(|h| h.target.clone()) {
if let Some(w) = self.tabs.iter().position(|t| t.id == tab) { return Some((w, pane)) }
}
diff --git a/tui/src/commands.rs b/tui/src/commands.rs
index 065353984..ff669ece5 100644
--- a/tui/src/commands.rs
+++ b/tui/src/commands.rs
@@ -585,6 +585,7 @@ fn run_queue(app: &mut App, mut queue: Queue) {
let focus = |app: &App| app.tabs.iter().chain(app.sessions.iter().flat_map(|s| s.tabs.iter())).map(|t| (t.id.clone(), t.focus)).collect::<Vec<_>>();
let before_focus = selecting.then(|| focus(app));
let pending_before = app.pending_hooks.len();
+ let shell_before = app.starting_shell.clone();
app.chain_follows = !queue.is_empty();
// A hook about a session not in front (its own after- hook): run there.
let there = hook.as_ref().and_then(|h| h.session).filter(|s| *s != app.session_id && app.swap_back.is_none() && app.sessions.iter().any(|x| x.id == *s && x.mirror.is_none()));
@@ -599,6 +600,8 @@ fn run_queue(app: &mut App, mut queue: Queue) {
}
None => run_words(app, &words),
}
+ let creates_pane = words.first().and_then(|w| crate::cmd::find(w).ok()).is_some_and(|e| matches!(e.name, "new-session" | "new-window" | "split-window"));
+ let started_shell = app.starting_shell.as_ref().filter(|_| creates_pane).filter(|current| shell_before.as_ref().is_none_or(|before| !std::sync::Arc::ptr_eq(before, current))).cloned();
// cmdq_fire_command: a command that failed fires command-error, one that did not its
// after- hook — not a command a hook ran.
let selected = before_focus.as_ref().is_none_or(|before| *before != focus(app));
@@ -606,6 +609,7 @@ fn run_queue(app: &mut App, mut queue: Queue) {
if words.first().and_then(|w| crate::cmd::find(w).ok()).is_some_and(|e| e.name == "new-session") {
hooks.extend(app.pending_hooks.split_off(pending_before.min(app.pending_hooks.len())));
}
+ let made_hooks: Vec<_> = hooks.iter().filter_map(|item| item.hook.as_ref()).filter(|state| state.made).cloned().collect();
app.origin = None;
app.mouse_ev = saved;
app.hook_state = saved_hook;
@@ -615,15 +619,39 @@ fn run_queue(app: &mut App, mut queue: Queue) {
// A shell on its way (new-session, new-window, split-window …): what comes after it
// waits for its pane, as tmux's queue has the pane before the next command runs —
// and so does the shell that ran the chain.
- if !queue.is_empty() && app.starting_shell.is_some() {
- let (tx, rx) = tokio::sync::oneshot::channel::<()>();
- app.shell_waiters.push((app.starting_shell.as_ref().unwrap().clone(), tx));
- let waiting = (app.capture.take(), app.capture_err.take(), app.cli_tx.take(), app.cli_code, app.cli_cwd.clone(), app.cli_size);
- app.spawn(async move { let _ = tokio::time::timeout(std::time::Duration::from_secs(90), rx).await; }, move |app, _| {
- let (cap, err, tx, code, cwd, size) = waiting;
+ if let Some(request) = started_shell.filter(|_| !queue.is_empty() || app.capture.is_some()) {
+ let (tx, rx) = tokio::sync::oneshot::channel::<crate::app::ShellCompletion>();
+ app.shell_waiters.push((request, tx));
+ let waiting = (app.capture.take(), app.capture_err.take(), app.cli_tx.take(), app.cli_code, app.cli_cwd.clone(), app.cli_size, app.cli_stdin.take(), app.cli_outside);
+ app.spawn(async move {
+ tokio::time::timeout(std::time::Duration::from_secs(90), rx).await.ok().and_then(Result::ok)
+ .unwrap_or_else(|| Err("create pane did not complete".into()))
+ }, move |app, result| {
+ let (mut cap, mut err, tx, code, cwd, size, stdin, outside) = waiting;
let from_shell = cap.is_some();
- if from_shell { app.capture = cap; app.capture_err = err; app.cli_tx = tx; app.cli_code = code; app.cli_cwd = cwd; app.cli_size = size }
- run_queue(app, queue);
+ let succeeded = result.is_ok();
+ let (out, errors) = match result {
+ Ok((out, (session, tab, pane))) => {
+ // Freeze this command's hooks to its own pane, including hooks that
+ // themselves suspend for run-shell or if-shell.
+ for item in &mut queue {
+ if let Some(state) = item.hook.as_mut().filter(|state| made_hooks.iter().any(|made| std::sync::Arc::ptr_eq(made, state))) {
+ let state = std::sync::Arc::make_mut(state);
+ state.target = Some((tab.clone(), pane)); state.session = Some(session); state.made = false;
+ }
+ }
+ (out, Vec::new())
+ }
+ Err(error) => (Vec::new(), vec![error]),
+ };
+ if from_shell {
+ cap.as_mut().unwrap().extend(out);
+ err.get_or_insert_with(Vec::new).extend(errors);
+ app.capture = cap; app.capture_err = err; app.cli_tx = tx;
+ app.cli_code = if succeeded { code } else { 1 };
+ app.cli_cwd = cwd; app.cli_size = size; app.cli_stdin = stdin; app.cli_outside = outside;
+ }
+ if succeeded { run_queue(app, queue) }
if from_shell && app.capture.is_some() { app.finish_cli() }
});
return;
@@ -1835,10 +1863,21 @@ fn run_words_in(app: &mut App, words: &[String]) {
let (sid, sname, wid, w) = (app.session_id, app.session_name(), app.tabs[app.active].wid(), app.tabs[app.active].name.clone());
notify_session(app, "window-linked", sid, &sname, Some((wid, w)));
}
- // -d: made, not visited: its shell starts there, and you stay where you were.
- if flag(words, "-d") { app.return_to = Some((was_id, last_before)) }
if flag(words, "-P") { app.print_new = Some(opt(words, "-F").unwrap_or_else(|| "#{session_name}:#{window_index}.#{pane_index}".into())) }
- input::new_shell_from(app, from, Placement::Auto(None), cwd, command);
+ // The reply can arrive after another window was selected or created.
+ // Bind it to this window, never to the later active window.
+ app.tab_mut().home = false;
+ let tab = app.tab().id.clone();
+ input::new_shell_from(app, from, Placement::Fill(tab), cwd, command);
+ // -d never visits the new window, even while its shell is still being created.
+ // A later completion must not restore stale selection or last-window history.
+ if flag(words, "-d") {
+ if let Some(i) = app.tabs.iter().position(|t| t.id == was_id) {
+ app.active = i; app.lastw = last_before;
+ app.home_order.borrow_mut().clear();
+ app.fit_panes();
+ }
+ }
}
"split-window" => {
// tmux's split-window [-bdfhIvPZ] [-c dir] [-l size] [-t target] [-F fmt] [command]: a
diff --git a/tui/src/input.rs b/tui/src/input.rs
index 58c3c59a3..7afa8a41c 100644
--- a/tui/src/input.rs
+++ b/tui/src/input.rs
@@ -1071,7 +1071,7 @@ pub fn popup(app: &mut App, (x, y, w, h): (u16, u16, u16, u16), border: bool, cw
let machine = shell_machine(app, focused.as_ref());
let live = focused.as_ref().and_then(|(m, a)| app.find_pane(m, a)).and_then(|(_, p)| app.panes.get(&p)).and_then(|p| p.cwd.clone().or_else(|| p.live_path.clone()));
let cwd = cwd.or(live).or_else(|| focused.as_ref().and_then(|(m, a)| app.fleet.agent(m, a)).map(|a| a.cwd.clone()).filter(|c| !c.is_empty()));
- let Some(link) = app.link(&machine) else { app.say("That machine is not connected", theme::DANGER); return };
+ let Some(link) = app.link(&machine) else { app.print_new = None; return app.error("That machine is not connected") };
let mut payload = json!({ "engine": "terminal", "creationId": uuid::Uuid::new_v4().to_string(), "bypassPermission": false });
if let Some(cwd) = &cwd { payload["cwd"] = json!(cwd) }
configure_local_shell(app, &machine, &mut payload);
@@ -1169,7 +1169,7 @@ pub fn new_shell_from(app: &mut App, focused: Option<(String, String)>, placemen
// The folder: -c, else where the pane's shell says it is now (OSC 7), else where it started.
let live = focused.as_ref().and_then(|(m, a)| app.find_pane(m, a)).and_then(|(_, p)| app.panes.get(&p)).and_then(|p| p.cwd.clone().or_else(|| p.live_path.clone()));
let cwd = cwd.or(live).or_else(|| focused.as_ref().and_then(|(m, a)| app.fleet.agent(m, a)).map(|a| a.cwd.clone()).filter(|c| !c.is_empty()));
- let Some(link) = app.link(&machine) else { app.say("That machine is not connected", theme::DANGER); return };
+ let Some(link) = app.link(&machine) else { app.print_new = None; return app.error("That machine is not connected") };
let mut payload = json!({ "engine": "terminal", "creationId": uuid::Uuid::new_v4().to_string(), "bypassPermission": false });
if let Some(cwd) = &cwd { payload["cwd"] = json!(cwd) }
configure_local_shell(app, &machine, &mut payload);
@@ -1186,6 +1186,9 @@ pub fn new_shell_from(app: &mut App, focused: Option<(String, String)>, placemen
app.starting_shell = Some(buffered.clone());
let tab = match &placement { Placement::Fill(id) => id.clone(), Placement::At(at) => at.tab.clone(), _ => app.tab().id.clone() };
app.shell_inputs.insert(tab, buffered.clone());
+ // Completion state belongs to this request, including concurrent -d/-P callers.
+ let print_new = app.print_new.take();
+ let from_cli = app.capture.is_some();
// The session it was asked for in (a command's `-t work:` puts another in front for a moment):
// where it goes when it comes, in front again for as long as that takes.
// (A window's own: the session that has it — new -d's new session is not the one in front.)
@@ -1203,92 +1206,72 @@ pub fn new_shell_from(app: &mut App, focused: Option<(String, String)>, placemen
let back = app.session_id;
app.swap_back = Some(back);
app.swap_session(session);
- shell_made(app, machine, placement, reply, &buffered);
+ shell_made(app, machine, placement, reply, &buffered, print_new, from_cli);
app.swap_back = None;
app.swap_session(back);
app.fit_panes();
app.save_sessions();
return;
}
- shell_made(app, machine, placement, reply, &buffered);
+ shell_made(app, machine, placement, reply, &buffered, print_new, from_cli);
});
}
-/// A shell the machine made (agent_create's reply): into its place.
fn take_shell_input(app: &mut App, buffered: &crate::app::ShellInput) -> Vec<Vec<u8>> {
if app.starting_shell.as_ref().is_some_and(|current| std::sync::Arc::ptr_eq(current, buffered)) { app.starting_shell = None }
app.shell_inputs.retain(|_, current| !std::sync::Arc::ptr_eq(current, buffered));
std::mem::take(&mut *buffered.lock().unwrap())
}
-fn shell_made(app: &mut App, machine: String, placement: Placement, reply: Result<serde_json::Value, crate::daemon::RpcError>, buffered: &crate::app::ShellInput) {
- let typed = take_shell_input(app, buffered);
- shell_placed(app, machine, placement, reply, typed);
- // Release only the commands waiting for this shell; another request may still be pending.
+/// A shell the machine made (agent_create's reply): into its place.
+fn shell_made(app: &mut App, machine: String, placement: Placement, reply: Result<serde_json::Value, crate::daemon::RpcError>, buffered: &crate::app::ShellInput, print_new: Option<String>, from_cli: bool) {
+ let typed = std::mem::take(&mut *buffered.lock().unwrap());
+ let result = shell_placed(app, machine, placement, reply, typed, print_new);
+ // Keep the pending window's initial size through placement and its first stream open.
+ if app.starting_shell.as_ref().is_some_and(|current| std::sync::Arc::ptr_eq(current, buffered)) { app.starting_shell = None }
+ app.shell_inputs.retain(|_, current| !std::sync::Arc::ptr_eq(current, buffered));
+ if !from_cli {
+ match &result {
+ Ok((out, _)) => for line in out { app.say(line.clone(), theme::WARN) },
+ Err(error) => app.say(error.clone(), theme::DANGER),
+ }
+ }
+ // Release only this request's waiters, carrying its output, target and failure too.
for (request, tx) in std::mem::take(&mut app.shell_waiters) {
- if std::sync::Arc::ptr_eq(&request, buffered) { let _ = tx.send(()); }
+ if std::sync::Arc::ptr_eq(&request, buffered) { let _ = tx.send(result.clone()); }
else { app.shell_waiters.push((request, tx)); }
}
}
-fn shell_placed(app: &mut App, machine: String, placement: Placement, reply: Result<serde_json::Value, crate::daemon::RpcError>, typed: Vec<Vec<u8>>) {
- match reply {
- Ok(reply) => {
- let Some(id) = reply.pointer("/agent/id").and_then(|v| v.as_str()) else { app.say("The machine made no shell", theme::DANGER); return };
- app.fleet.agents.insert((machine.clone(), id.to_string()), crate::fleet::agent_from(&machine, &reply["agent"], None));
- app.shells.insert((machine.clone(), id.to_string()));
- app.open_agent(&machine, id, placement);
- // new-window -d: made in the background; back to where you were — never left, as
- // tmux sees it (nothing cleared or raised there). The new window is activity
- // (window_create), flagged as it is not the current one.
- if let Some((back, last)) = app.return_to.take() {
- if let Some(i) = app.tabs.iter().position(|t| t.id == back) {
- app.active = i;
- app.lastw = last;
- app.home_order.borrow_mut().clear();
- if let Some(f) = app.tabs[i].focus { app.seen(f) }
- app.fit_panes();
- }
- if let Some((w, _)) = app.find_pane(&machine, id) { app.tabs[w].touch(); app.alert(w, crate::app::ACTIVITY) }
- }
- if let Some((w, pane)) = app.find_pane(&machine, id) {
- app.last_made = Some((app.tabs[w].id.clone(), pane));
- if let Some(p) = app.panes.get_mut(&pane) {
- p.queued.extend(typed);
- p.start_command = reply.pointer("/agent/startCommand").and_then(serde_json::Value::as_str).map(str::to_string);
- }
- // -P: what was made, printed (to the shell waiting on it).
- if let Some(fmt) = app.print_new.take() {
- let line: String = crate::format::spans_for_pane(app, &fmt, w, pane, ratatui::style::Style::default()).into_iter().map(|s| s.content.into_owned()).collect();
- match app.held_reply.take() { Some(tx) => { let _ = tx.send((vec![line], Vec::new(), 0)); } None => app.say(line, theme::WARN) }
- }
- }
- // -P for a pane made in a session not in front (new -d -s x -P, libtmux's every
- // session): printed from there. The shell waiting on it is always answered — every
- // command after it waits behind it.
- if let Some(fmt) = app.print_new.take() {
- let line = match app.find_pane_anywhere(&machine, id) {
- Some((sid, _, pane)) if sid != app.session_id => {
- let (back, before) = (app.session_id, app.swap_back);
- app.swap_back = Some(back);
- let line = if app.swap_session(sid) {
- app.tabs.iter().position(|t| t.panes().contains(&pane)).map(|w| crate::format::spans_for_pane(app, &fmt, w, pane, ratatui::style::Style::default()).into_iter().map(|s| s.content.into_owned()).collect::<String>()).unwrap_or_default()
- } else { String::new() };
- app.swap_session(back);
- app.swap_back = before;
- line
- }
- _ => String::new(),
- };
- match app.held_reply.take() { Some(tx) => { let _ = tx.send((vec![line], Vec::new(), 0)); } None => app.say(line, theme::WARN) }
- }
- }
- Err(e) => {
- if let Some(tx) = app.held_reply.take() { let _ = tx.send((Vec::new(), vec![format!("create pane failed: {e}")], 1)); }
- app.print_new = None;
- app.say(format!("Could not start a shell: {e}"), theme::DANGER)
- }
- }
+fn shell_placed(app: &mut App, machine: String, placement: Placement, reply: Result<serde_json::Value, crate::daemon::RpcError>, typed: Vec<Vec<u8>>, print_new: Option<String>) -> crate::app::ShellCompletion {
+ let reply = reply.map_err(|e| format!("create pane failed: {e}"))?;
+ let id = reply.pointer("/agent/id").and_then(|v| v.as_str()).ok_or("The machine made no shell")?;
+ app.fleet.agents.insert((machine.clone(), id.to_string()), crate::fleet::agent_from(&machine, &reply["agent"], None));
+ app.shells.insert((machine.clone(), id.to_string()));
+ let new_window = matches!(&placement, Placement::Fill(_));
+ app.open_agent(&machine, id, placement);
+ let (session, _, pane) = app.find_pane_anywhere(&machine, id).ok_or("create pane failed: target window or pane disappeared")?;
+ if let Some(p) = app.panes.get_mut(&pane) {
+ p.queued.extend(typed);
+ p.start_command = reply.pointer("/agent/startCommand").and_then(serde_json::Value::as_str).map(str::to_string);
+ }
+ // A new session's first pane may belong to a session not currently in front.
+ let (back, before) = (app.session_id, app.swap_back);
+ if session != back { app.swap_back = Some(back); app.swap_session(session); }
+ let Some(w) = app.tabs.iter().position(|t| t.panes().contains(&pane)) else {
+ if session != back { app.swap_session(back); app.swap_back = before; }
+ return Err("create pane failed: target session disappeared".into())
+ };
+ let tab = app.tabs[w].id.clone();
+ if new_window {
+ app.tabs[w].touch();
+ if w != app.active { app.alert(w, crate::app::ACTIVITY) }
+ }
+ let out = print_new.map(|fmt| {
+ crate::format::spans_for_pane(app, &fmt, w, pane, ratatui::style::Style::default()).into_iter().map(|s| s.content.into_owned()).collect()
+ }).into_iter().collect();
+ if session != back { app.swap_session(back); app.swap_back = before; }
+ Ok((out, (session, tab, pane)))
}
fn create(app: &mut App, machine: String, what: What, cwd: Option<String>, message: Option<String>) { create_in(app, machine, what, cwd, message, false) }
diff --git a/tui/src/ipc.rs b/tui/src/ipc.rs
index 9aaf84788..ab4454bbe 100644
--- a/tui/src/ipc.rs
+++ b/tui/src/ipc.rs
@@ -157,7 +157,7 @@ fn accept(listener: tokio::net::UnixListener, sink: mpsc::UnboundedSender<Event>
if app.capture.is_some() { app.finish_cli() }
});
let _ = sink.send(Event::Apply(Box::new(move |app: &mut crate::app::App| app.run_cli(&asked, job))));
- let (mut out, err, code) = rx.await.unwrap_or_default();
+ let (mut out, err, code) = rx.await.unwrap_or_else(|_| (Vec::new(), vec!["command did not complete".into()], 1));
// A last line marked bare (show-buffer's data without a newline) is printed bare.
let bare = out.last().map(|l| l.ends_with(crate::app::BARE)).unwrap_or(false);
if let Some(l) = out.last_mut() { if let Some(s) = l.strip_suffix(crate::app::BARE) { *l = s.to_string() } }
diff --git a/tui/tests/native-terminal.py b/tui/tests/native-terminal.py
index 27c6d0b59..200590ff9 100644
--- a/tui/tests/native-terminal.py
+++ b/tui/tests/native-terminal.py
@@ -137,6 +137,170 @@ def stop_servers():
wait(lambda: not owned(), 'native processes cleaned')
+def async_creation():
+ """Hold only our supervisor so pending creation ownership is deterministic."""
+ requests = []
+ stopped = None
+
+ def start(*args):
+ process = subprocess.Popen(argv('hn', *args), env=ENV, cwd=BASE,
+ text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ requests.append(process)
+ return process
+
+ def result(process, timeout=8):
+ out, err = process.communicate(timeout=timeout)
+ return process.returncode, out, err
+
+ def quick(*args):
+ reply = result(start(*args), timeout=3)
+ assert reply[0] == 0, (args, reply)
+ return reply[1].strip()
+
+ def reserved(index):
+ return str(index) in quick('list-windows', '-t', 'async', '-F', '#I').splitlines()
+
+ def supervisor():
+ found = [pid for pid, command in owned() if command.endswith(' --local-server')]
+ assert len(found) == 1, found
+ return found[0]
+
+ def pause():
+ nonlocal stopped
+ assert stopped is None
+ stopped = supervisor()
+ os.kill(stopped, signal.SIGSTOP)
+
+ def resume():
+ nonlocal stopped
+ if stopped is not None:
+ try:
+ os.kill(stopped, signal.SIGCONT)
+ except ProcessLookupError:
+ pass
+ stopped = None
+
+ def children(pid):
+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,ppid='], text=True)
+ return {int(child) for child, parent in (row.split() for row in rows.splitlines())
+ if int(parent) == pid}
+
+ def creation(index, printed):
+ command = f'printf "ASYNC_{index}\\n"; exit 7'
+ args = ['new-window', '-d', '-t', f'async:{index}']
+ if printed:
+ args += ['-P', '-F', f'REPLY_{index}:#I:#{{pane_start_command}}']
+ return [*args, command]
+
+ focus_format = '#{window_index}:#{session_stack}'
+ focus_args = ('display', '-p', '-t', 'async', focus_format)
+ try:
+ both('new-session', '-d', '-s', 'async')
+ both('new-window', '-d', '-t', 'async:1', '-n', 'anchor')
+ wait(lambda: same('list-windows', '-t', 'async', '-F', '#I:#{window_panes}') == '0:1\n1:1', 'async anchors ready')
+ both('set', '-g', 'remain-on-exit', 'on')
+ both('select-window', '-t', 'async:1')
+ both('select-window', '-t', 'async:0')
+ before = same(*focus_args)
+
+ # The plain command must wait too; the two -P requests must each own their output.
+ pause()
+ pending = []
+ for index, printed in ((4, False), (5, True), (6, True)):
+ args = creation(index, printed)
+ process = start(*args)
+ wait(lambda index=index: reserved(index), f'pending window {index} reserved')
+ pending.append((index, args, process))
+ assert quick(*focus_args) == before, ('detached creation changed focus/history', index)
+ assert quick('display', '-p', 'READ_WHILE_PENDING') == 'READ_WHILE_PENDING'
+ assert all(process.poll() is None for _, _, process in pending), 'creation answered before its shell existed'
+
+ # A later explicit selection wins even when the earlier creation replies arrive later.
+ both('select-window', '-t', 'async:1')
+ selected = same(*focus_args)
+ expected = {}
+ for index, args, _ in pending:
+ reference = cli('tmux', *args)
+ expected[index] = reference.returncode, reference.stdout, reference.stderr
+ resume()
+ for index, _, process in pending:
+ reply = result(process)
+ assert reply == expected[index], (index, reply, expected[index])
+ wait(lambda index=index: same('list-panes', '-t', f'async:{index}', '-F', '#{pane_dead}:#{pane_dead_status}') == '1:7', f'async exit {index}')
+ assert f'ASYNC_{index}' in same('display', '-p', '-t', f'async:{index}', '#{pane_start_command}')
+ for kind in ('hn', 'tmux'):
+ wait(lambda kind=kind, index=index: cli(kind, 'capture-pane', '-p', '-S', '-1000', '-t', f'async:{index}').stdout.count(f'ASYNC_{index}') == 1,
+ f'{kind} async output {index}')
+ capture = cli(kind, 'capture-pane', '-p', '-S', '-1000', '-t', f'async:{index}').stdout
+ assert all(f'ASYNC_{other}' not in capture for other in (4, 5, 6) if other != index), (kind, index, capture)
+ assert same(*focus_args) == selected, 'a delayed creation stole the newer selection/history'
+
+ # Two completions can arrive before either hook continuation: its target must remain
+ # the pane that request made, including across run-shell's asynchronous wait.
+ both('set', '-g', '@async_created', '')
+ both('set-hook', '-g', 'after-new-window',
+ 'run-shell "sleep 0.15"; set -agF @async_created "#{window_index}:#{pane_start_command}|"')
+ pause()
+ pending = []
+ for index in (8, 9):
+ args = creation(index, True)
+ process = start(*args)
+ wait(lambda index=index: reserved(index), f'hooked pending window {index} reserved')
+ pending.append((index, args, process))
+ expected = {}
+ for index, args, _ in pending:
+ reference = cli('tmux', *args)
+ expected[index] = reference.returncode, reference.stdout, reference.stderr
+ resume()
+ for index, _, process in pending:
+ reply = result(process)
+ assert reply == expected[index], (index, reply, expected[index])
+ wait(lambda index=index: same('list-panes', '-t', f'async:{index}', '-F', '#{pane_dead}:#{pane_dead_status}') == '1:7', f'hooked async exit {index}')
+ expected_hooks = sorted(f'{index}:' + cli('tmux', 'display', '-p', '-t', f'async:{index}', '#{pane_start_command}').stdout.strip() for index in (8, 9))
+ for kind in ('hn', 'tmux'):
+ wait(lambda kind=kind: sorted(filter(None, cli(kind, 'show', '-gv', '@async_created').stdout.strip().split('|'))) == expected_hooks,
+ f'{kind} delayed creation hooks keep their own targets')
+ assert same(*focus_args) == selected, 'hooked detached creation changed focus/history'
+ both('set-hook', '-gu', 'after-new-window')
+
+ # If the reserved target is killed before the RPC responds, failure belongs to that
+ # caller and the newly returned shell must be deleted. Real tmux creates synchronously;
+ # compare its final killed-window state, not this artificial cancellation's exit code.
+ local_pid = supervisor()
+ baseline_children = children(local_pid)
+ pause()
+ args = ['new-window', '-d', '-P', '-t', 'async:20', 'exec sleep 30']
+ cancelled = start(*args)
+ wait(lambda: reserved(20), 'cancelled target reserved')
+ assert cancelled.poll() is None, 'cancelled creation answered before completion'
+ quick('kill-window', '-t', 'async:20')
+ cli('tmux', *args)
+ cli('tmux', 'kill-window', '-t', 'async:20')
+ resume()
+ code, out, err = result(cancelled)
+ assert code != 0 and err and not out, ('killed target must fail its caller', code, out, err)
+ assert '20' not in same('list-windows', '-t', 'async', '-F', '#I').splitlines()
+ wait(lambda: children(local_pid) == baseline_children, 'cancelled shell left no supervisor child')
+ assert same(*focus_args) == selected
+ stop_servers()
+ print('PASS concurrent creation replies, detached selection, delayed hooks and cancelled-target cleanup', flush=True)
+ finally:
+ resume()
+ for process in requests:
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.communicate(timeout=3)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.communicate(timeout=3)
+ for kind in ('hn', 'tmux'):
+ try:
+ cli(kind, 'kill-server', check=False)
+ except subprocess.TimeoutExpired:
+ pass
+
+
with socket.socket() as probe:
probe.bind(('127.0.0.1', PORT))
try:
@@ -214,6 +378,8 @@ try:
ui.stop()
print('PASS retained exits/signals, hooks, history, crash recovery and respawn', flush=True)
+ async_creation()
+
for delay in (0, .1):
for kind in ('hn', 'tmux'):
marker = BASE / f'{kind}-typeahead'