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.

feat(hn): match the desktop New Harness popup (#476)

Deef252efd7735e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 48214a5da..5099ec2ef 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -159,6 +159,11 @@ jobs:
HN_PANE_UI_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui
HN_PANE_UI_PORT: 19783
run: python3 -u tests/pane-ui.py
+ - name: New Harness popup, draft and launch recovery
+ env:
+ HN_NEW_UI_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui
+ run: python3 -u tests/new-harness.py
+
- name: Layout keys and shared desk synchronization
env:
HN_LAYOUT_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui
diff --git a/docs/research/2026-09-29-hn-new-harness-agent.png b/docs/research/2026-09-29-hn-new-harness-agent.png
new file mode 100644
index 000000000..681dbe6e6
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-agent.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness-form.png b/docs/research/2026-09-29-hn-new-harness-form.png
new file mode 100644
index 000000000..9f0aceba9
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-form.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness-light.png b/docs/research/2026-09-29-hn-new-harness-light.png
new file mode 100644
index 000000000..889604dcd
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-light.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness-narrow.png b/docs/research/2026-09-29-hn-new-harness-narrow.png
new file mode 100644
index 000000000..90458e9ca
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-narrow.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness-options.png b/docs/research/2026-09-29-hn-new-harness-options.png
new file mode 100644
index 000000000..b21d9730e
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-options.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness-project.png b/docs/research/2026-09-29-hn-new-harness-project.png
new file mode 100644
index 000000000..0ade850c3
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-project.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness-retry.png b/docs/research/2026-09-29-hn-new-harness-retry.png
new file mode 100644
index 000000000..729d21238
Binary files /dev/null and b/docs/research/2026-09-29-hn-new-harness-retry.png differ
diff --git a/docs/research/2026-09-29-hn-new-harness.md b/docs/research/2026-09-29-hn-new-harness.md
new file mode 100644
index 000000000..b1e564bb5
--- /dev/null
+++ b/docs/research/2026-09-29-hn-new-harness.md
@@ -0,0 +1,57 @@
+# New Harness popup in hn
+
+`Ctrl-b N` now opens the desktop's compact Agent / Project / Options / New Harness
+form instead of advancing through separate pickers. Lowercase `Ctrl-b n` remains
+next window. The layout follows the desktop form and screenshots reviewed on
+September 29, including side choosers and the collapsed Options row.
+
+![Compact form](2026-09-29-hn-new-harness-form.png)
+
+![Agent chooser](2026-09-29-hn-new-harness-agent.png)
+
+![Project chooser](2026-09-29-hn-new-harness-project.png)
+
+Options exposes Model, agent-specific Approvals, Codex Profile, Branch and Worktree.
+Project owns machine selection. Installed Store harnesses ask for a compatible
+coding agent. Git discovery canonicalizes linked worktrees to their repository;
+fresh Git work defaults to a worktree from main. The form uses the existing daemon
+RPCs and project/model payloads; it does not introduce a parallel launch protocol.
+
+Arrows preview a field's choices. Enter, Right or typing enters the chooser; Tab
+switches between form and chooser. Enter accepts a choice and returns to the launch
+action. Escape retraces nested choices and retains a dismissed draft. Mouse input
+uses the rendered row positions. Confirmed failures retain their choices and reuse
+any prepared project folder with a fresh receipt on deliberate retry. Lost replies
+retain the original receipt and offer Check status, so pending or unknown outcomes
+cannot duplicate a launch. Explicit model routes, profiles and package compatibility
+are rechecked on the destination machine.
+
+![Options](2026-09-29-hn-new-harness-options.png)
+
+![Failed launch, draft retained](2026-09-29-hn-new-harness-retry.png)
+
+The terminal version uses readable text and a selection marker without reverse
+video. A narrow terminal shows the active chooser in the form's column.
+
+![Narrow chooser](2026-09-29-hn-new-harness-narrow.png)
+
+![Light appearance](2026-09-29-hn-new-harness-light.png)
+
+## Validation
+
+- 170 Rust release unit tests pass, including launch payloads, agent-specific modes,
+ stale callbacks, draft retention and rendering bounds down to a one-cell terminal.
+- The new private-terminal suite passes six groups covering keyboard/mouse input,
+ paste isolation, persisted failure/retry receipts, lost replies, reconnect recovery,
+ duplicate prevention, folder browsing, worktree branches, explicit models, Codex profiles, Store harnesses, Terminal,
+ draft restoration and narrow/light presentation.
+- The existing pane UI suite passes all 11 groups, and the existing end-to-end suite
+ passes. The popup suite is also added to the manual CI workflow.
+
+These captures use synthetic projects and conversations in disposable tmux sessions,
+a temporary HOME, explicit private socket names and fixture ports. No real engine,
+account, project checkout or existing user pane was launched or modified by the
+interaction tests. Actual daemon payload names were checked against
+`cli/src/lib/projectFolder.ts`, `cli/src/lib/newAgentModel.ts` and the desktop launch
+controller. Native app launch, real model inference and Store installation are not
+part of this validation.
diff --git a/tui/README.md b/tui/README.md
index 187969dcd..dfc810df2 100644
--- a/tui/README.md
+++ b/tui/README.md
@@ -126,12 +126,33 @@ Harness's own, only on keys tmux leaves unbound (every tmux key does what tmux d
| | |
|---|---|
| `C-b a` / `C-b A` | the next harness that needs you (`next-harness`) / all those waiting on you (`M-1…9` answers from the list; `M-a` types an answer — an option's number, several for a multi-choice question, `1,3`, or your own words) |
-| `C-b N` `C-b T` | new harness (an agent: machine, agent, folder — `M-w` for a new git worktree of it, on a branch of its own — then its first message) / new terminal. Agents start in `@hn-permission-mode` (auto unless you `set -g @hn-permission-mode plan`, `acceptEdits`, `ask` …) |
+| `C-b N` `C-b T` | New Harness popup / new terminal. The popup keeps Agent, Project and Options together, with searchable choices. Options match desktop: Model, Approvals, applicable Profile, Branch and Worktree. |
| `C-b I` `C-b @` `C-b S` | models, machines, the Harness Store |
| `C-b g` `C-b B` | send a task (Harness picks the harness) / broadcast to the window |
| `C-b R` `C-b P` `C-b K` | restart, pause, clone the harness |
-In every list, fzf's keys: `C-j/C-k` `C-n/C-p` move, `Tab` marks, `C-/` toggles the preview,
+`C-b N` opens the compact desktop-style New Harness form with Agent, Project, collapsed
+Options and New Harness. The initial destination is the local machine, with successful agent
+and project choices remembered. Explicit project commands keep their destination. Enter starts
+with the displayed choices; Up/Down moves between fields and previews their chooser. Enter,
+Right or typing enters the chooser. Tab switches between the form and chooser; Enter accepts
+an item and returns to New Harness. A second Enter starts it. Lowercase `C-b n` remains next window.
+
+Agent combines coding agents and installed Store harnesses; a Store harness then offers its
+compatible coding agents. Project offers Clone Repository, Open Folder, New Folder and recent
+machine/folder pairs. Folder actions choose a machine first. Ctrl-L in the folder browser edits
+a path. Options contains Model, agent-specific Approvals, Codex Profile, Branch and Worktree.
+Git projects default to a new worktree from main, as on desktop; missing main requires a branch
+choice. Models and profiles are checked on the selected machine before starting.
+
+Choosers sit beside the form, or occupy its column in narrow terminals. Escape returns through
+nested choosers and preserves a dismissed draft. Confirmed failures keep the draft and reuse
+any prepared project folder on retry. A lost reply offers Check status for the original launch;
+repeated Enter cannot start another harness while its outcome is unknown. Input in the form
+never reaches a working pane. No reverse-video selection is used.
+
+
+In the harness and command lists, fzf's keys: `C-j/C-k` `C-n/C-p` move, `Tab` marks, `C-/` toggles the preview,
`S-↑/↓` scrolls it, `M-/` wraps long rows (`--wrap`), `C-a C-e C-w C-u` edit the query, `enter`
opens, `C-t` in a new window, `C-v` beside, `C-x` below, `esc` leaves. fzf's search syntax works
(`'exact ^prefix suffix$ !not a | b`), and its colours follow `FZF_DEFAULT_OPTS` (`--color=light`,
@@ -219,6 +240,7 @@ and `#{fleet_tokens}` (what it, and all of them, have used: `1.2M`), `#{pane_lin
`#{pane_todos}` (its plan's progress, `3/7`) and `#{pane_subagents}` (how many it has running),
`#{usage}` (the agent accounts' rate limits on the focused pane's machine: `claude 5h 42% week
18% · codex 5h 3%`) and `#{usage_high}` (the one nearest its limit, from 80% used).
+
The status line uses `#{usage_remaining_mark}`: `Claude 0% Codex 89%`, showing **remaining**
allowance for every subscription with quota data, even when healthy. Each figure is the lowest
remaining percentage across that account's reported windows. Amber starts at 20% left, red at
diff --git a/tui/src/app.rs b/tui/src/app.rs
index 68b1e770b..88797c616 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -513,6 +513,8 @@ pub struct App {
pub started: Instant,
pub daemon_down: bool,
pub dsh: HashMap<String, Vec<Value>>,
+ /// A dismissed New Harness draft, including any pending creation receipt.
+ pub new_harness_draft: Option<Box<crate::new_harness::Form>>,
/// Each harness's selectable models (`models_list`), for ⌥I.
pub models: HashMap<(String, String), Vec<Value>>,
/// Each machine's local models (the grid): downloaded, running, available.
@@ -956,6 +958,7 @@ impl App {
started: Instant::now(),
daemon_down: false,
dsh: HashMap::new(),
+ new_harness_draft: None,
models: HashMap::new(),
local_models: HashMap::new(),
rtt: HashMap::new(),
@@ -4539,7 +4542,7 @@ impl App {
/// before break-pane goes to its new window is looked at while the old one still is).
fn update_focus_in(&mut self, pane: u64, focused: &mut Vec<u64>, notify: bool, current: usize) {
let Some(w) = self.tabs.iter().position(|t| t.panes().contains(&pane)) else { return };
- let overlay = matches!(self.modal, Some(crate::modal::Modal::Menu(_)) | Some(crate::modal::Modal::Popup { .. }));
+ let overlay = matches!(self.modal, Some(crate::modal::Modal::Menu(_)) | Some(crate::modal::Modal::Popup { .. }) | Some(crate::modal::Modal::NewHarness(_)));
let focus_events = self.options.get("focus-events", "", None).as_deref() == Some("on");
let client = !focus_events || self.terminal_focused;
let is = w == current && self.tabs[w].focus == Some(pane) && client && !overlay;
diff --git a/tui/src/input.rs b/tui/src/input.rs
index 220e08d16..4896d3a37 100644
--- a/tui/src/input.rs
+++ b/tui/src/input.rs
@@ -44,7 +44,7 @@ pub fn handle(app: &mut App, event: CEvent) {
/// Overlays that type text keep every key (tmux's prompt ignores the prefix too).
fn typing(app: &App) -> bool {
- matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Picker { .. }) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }))
+ matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Picker { .. }) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }) | Some(Modal::NewHarness(_)))
}
fn on_key(app: &mut App, key: KeyEvent) {
@@ -129,7 +129,7 @@ fn on_key(app: &mut App, key: KeyEvent) {
}
// The prefix works over the lists too (they are tmux's choose modes); only a line being typed
// at the status line keeps it.
- let line_edit = matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }));
+ let line_edit = matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }) | Some(Modal::NewHarness(_)));
if !line_edit && (chord == app.keymap.prefix || Some(chord) == app.keymap.prefix2) {
app.status_redraws += 1;
app.prefix = true;
@@ -240,6 +240,7 @@ pub fn send_to_pane(app: &mut App, focus: u64, bytes: Vec<u8>) {
}
fn on_paste(app: &mut App, text: String) {
+ if let Some(Modal::NewHarness(form)) = &mut app.modal { crate::new_harness::paste(form, &text); return }
if let Some(Modal::Picker { picker, .. }) = &mut app.modal { for c in text.chars().filter(|c| !c.is_control()) { picker.type_char(c) } return }
if let Some(Modal::Prompt(prompt)) = &mut app.modal { prompt.value.push_str(&text.replace(['\r', '\n'], " ")); return }
app.tab_mut().home = false;
@@ -263,6 +264,7 @@ fn on_mouse(app: &mut App, mouse: MouseEvent) {
/// preview, whichever it is over; a click takes a row, a second one opens it; in the preview a
/// drag scrolls it and a drag on its border resizes it; a click outside the box closes it.
fn modal_mouse(app: &mut App, mouse: MouseEvent) {
+ if matches!(app.modal, Some(Modal::NewHarness(_))) { return crate::new_harness::mouse(app, mouse) }
// --no-mouse: a list the mouse does nothing to.
if theme::fzf_opts().no_mouse && matches!(app.modal, Some(Modal::Picker { .. })) { return }
let inside = |r: ratatui::layout::Rect| mouse.column >= r.x && mouse.column < r.x + r.width && mouse.row >= r.y && mouse.row < r.y + r.height;
@@ -573,7 +575,6 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {
// Its spinner turns while what it lists is still coming in, as fzf's does while it reads.
let busy = match kind {
PickerKind::Store => is_loading(&format!("dsh {}", app.fleet.local_id)),
- PickerKind::NewWhat { machine, .. } | PickerKind::NewFolder { machine, .. } => is_loading(&format!("dsh {machine}")),
PickerKind::Models => is_loading(&format!("grid {}", modal::models_machine(app))) || focused_agent(app).is_some_and(|(m, a)| is_loading(&format!("models {m} {a}"))),
_ => false,
};
@@ -663,22 +664,6 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {
// (While it loads the spinner turns and the list is blank, as fzf's is while it reads.)
if catalog.is_empty() { picker.empty = "Nothing in the Store yet.".into() }
}
- PickerKind::NewMachine => {
- let prefer = app.focused().and_then(|f| app.panes.get(&f)).map(|p| p.machine_id.clone()).unwrap_or(app.fleet.local_id.clone());
- picker.set_rows(modal::new_machine_rows(app, &prefer));
- picker.hints = vec![("enter", "choose")];
- }
- PickerKind::NewWhat { machine, .. } => {
- let catalog = app.dsh.get(machine).cloned().unwrap_or_default();
- picker.set_rows(modal::new_what_rows(&catalog));
- picker.status = app.fleet.machine_name(machine);
- picker.hints = vec![("enter", "choose")];
- }
- PickerKind::NewFolder { machine, .. } => {
- picker.set_rows(modal::new_folder_rows(app, machine));
- picker.status = app.fleet.machine_name(machine);
- picker.hints = vec![("enter", "choose"), ("M-w", "in a new worktree")];
- }
PickerKind::Route { .. } => {}
PickerKind::Output { title, lines } => {
picker.keep_order = true;
@@ -835,12 +820,7 @@ pub fn run(app: &mut App, command: &str) {
"help" => launch(app, "?", Filter::All),
"layout" => picker(app, PickerKind::Layout, "layout", ""),
"store" => launch(app, "*", Filter::All),
- "new" => {
- let usable: Vec<String> = app.fleet.machines.iter().filter(|m| m.usable()).map(|m| m.id.clone()).collect();
- if usable.len() > 1 { picker(app, PickerKind::NewMachine, "New Harness · where", "Machine…") }
- else if let Some(machine) = usable.first().cloned() { new_what(app, machine) }
- else { app.say("No machine is connected yet", theme::DANGER) }
- }
+ "new" => crate::new_harness::open(app, None, None),
"terminal" => {
let machine = focused_agent(app).map(|(m, _)| m).unwrap_or(app.fleet.local_id.clone());
create(app, machine, What { engine: "terminal".into(), dsh: None, label: "Terminal".into() }, None, None);
@@ -1012,7 +992,7 @@ fn agent_rpc_on(app: &mut App, machine: String, agent: String, ty: &'static str,
});
}
-fn load_dsh(app: &mut App, machine: String) {
+pub(crate) fn load_dsh(app: &mut App, machine: String) {
let Some(link) = app.link(&machine) else { return };
let id = machine.clone();
let mark = loading(format!("dsh {machine}"), true);
@@ -1047,6 +1027,7 @@ fn harness_preview(picker: &mut Picker) {
/// Rebuild the open overlay's rows (the fleet or a catalog moved under it).
pub fn refill(app: &mut App) {
+ if matches!(app.modal, Some(Modal::NewHarness(_))) { return crate::new_harness::refresh(app) }
// A delayed search/catalog reply may arrive after the picker has closed. It must not
// consume a command prompt, confirmation or copy mode that replaced that picker.
if !matches!(app.modal, Some(Modal::Picker { .. })) { return }
@@ -1059,11 +1040,7 @@ pub fn refill(app: &mut App) {
}
}
-fn new_what(app: &mut App, machine: String) {
- load_dsh(app, machine.clone());
- let name = app.fleet.machine_name(&machine);
- picker(app, PickerKind::NewWhat { machine, cwd: None }, &format!("new harness · {name}"), "Claude Code, Codex, a Store harness…");
-}
+fn new_what(app: &mut App, machine: String) { crate::new_harness::open(app, Some(machine), None) }
/// `agent_create`, then open it. [cwd] None with an agent = a new project folder.
/// tmux's split-window / new-window: a shell, now, on this pane's machine and in its folder
@@ -1284,7 +1261,7 @@ fn create(app: &mut App, machine: String, what: What, cwd: Option<String>, messa
/// @hn-permission-mode says (auto unless you set it: acceptEdits, plan, ask, full …).
fn create_in(app: &mut App, machine: String, what: What, cwd: Option<String>, message: Option<String>, worktree: bool) { create_opts(app, machine, what, cwd, message, worktree, NewOpts::default()) }
-fn create_opts(app: &mut App, machine: String, what: What, cwd: Option<String>, message: Option<String>, worktree: bool, opts: NewOpts) {
+pub(crate) fn create_opts(app: &mut App, machine: String, what: What, cwd: Option<String>, message: Option<String>, worktree: bool, opts: NewOpts) {
let Some(link) = app.link(&machine) else { return app.error("That machine is not connected") };
let terminal = what.engine == "terminal";
let mut payload = json!({ "engine": what.engine, "creationId": uuid::Uuid::new_v4().to_string(), "bypassPermission": !terminal });
@@ -1298,15 +1275,47 @@ fn create_opts(app: &mut App, machine: String, what: What, cwd: Option<String>,
if !terminal { payload["permissionMode"] = json!(app.options.get("@hn-permission-mode", "", None).filter(|m| !m.is_empty()).unwrap_or_else(|| "auto".into())) }
if let Some(message) = message.filter(|m| !m.trim().is_empty()) { payload["prompt"] = json!(message.trim()) }
if let Some(name) = opts.name.as_ref().filter(|n| !n.is_empty()) { payload["name"] = json!(name) }
+ if let Some(extra) = opts.extra.as_ref().and_then(|v| v.as_object()) { for (key, value) in extra { payload[key] = value.clone(); } }
+ if let Some(form_id) = &opts.form_id {
+ let Some(Modal::NewHarness(form)) = &mut app.modal else { return };
+ if &form.id != form_id || form.attempt.is_some() { return }
+ form.attempt = Some(crate::new_harness::Creation {
+ id: payload["creationId"].as_str().unwrap().into(), machine: machine.clone(), session: app.session_id,
+ });
+ form.starting = true; form.error.clear();
+ }
// (From a shell: nothing said on the way — a message there is the command's error.)
if app.capture.is_none() { app.say(format!("Starting {} on {}…", what.label, app.fleet.machine_name(&machine)), theme::SOFT) }
- app.modal = None;
+ if opts.form_id.is_none() { app.modal = None; }
// -P: the shell that asked waits for it, and is told where it is (as new-window -P).
if opts.print.is_some() { app.print_new = opts.print.clone() }
let session = app.session_id;
- app.spawn(async move { link.rpc("agent_create", payload, Duration::from_secs(180)).await }, move |app, reply| match reply {
+ let timeout = Duration::from_secs(if opts.form_id.is_some() { 20 } else { 180 });
+ app.spawn(async move { link.rpc("agent_create", payload, timeout).await }, move |app, reply| {
+ creation_finished(app, machine, session, opts, reply, false);
+ });
+}
+
+pub(crate) fn check_creation(app: &mut App, form_id: String, attempt: crate::new_harness::Creation) {
+ let opts = NewOpts { form_id: Some(form_id), ..Default::default() };
+ let Some(link) = app.link(&attempt.machine) else {
+ return creation_finished(app, attempt.machine, attempt.session, opts, Err(crate::daemon::RpcError::new("DISCONNECTED", "")), true);
+ };
+ app.spawn(async move {
+ link.rpc("agent_create_status", json!({"creationId":attempt.id}), Duration::from_secs(10)).await
+ }, move |app, reply| {
+ creation_finished(app, attempt.machine, attempt.session, opts, reply, true);
+ });
+}
+
+fn creation_finished(app: &mut App, machine: String, session: u32, opts: NewOpts, reply: Result<serde_json::Value, crate::daemon::RpcError>, checking: bool) {
+ if let Some(id) = &opts.form_id {
+ if !crate::new_harness::creation_reply(app, id, &reply, checking) { return }
+ }
+ match reply {
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"]); }
app.fleet.agents.insert((machine.clone(), id.to_string()), crate::fleet::agent_from(&machine, &reply["agent"], None));
// A new harness is a new window (as C-b c's shell is), or the empty one here —
// in the session it was asked for; -d: not gone to.
@@ -1324,19 +1333,22 @@ fn create_opts(app: &mut App, machine: String, what: What, cwd: Option<String>,
app.toast = None;
} 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())); }
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}"))); }
app.say(format!("Could not start it: {e}"), theme::DANGER)
}
- });
+ }
}
fn modal_key(app: &mut App, key: KeyEvent) {
let Some(modal) = app.modal.take() else { return };
match modal {
+ Modal::NewHarness(form) => crate::new_harness::key(app, form, key),
Modal::Confirm { command, key: yes, enter_yes, .. } => {
// tmux: the confirm key (y, or -c's) runs it, Enter too with -y; any other says no.
if key.code == KeyCode::Char(yes) || (enter_yes && key.code == KeyCode::Enter) { commands::execute(app, &command) }
@@ -2087,8 +2099,6 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, mut picker: Picker
KeyCode::Char('o') if ctrl => { choose(app, kind, picker, Choice::Open); return }
KeyCode::Char('l') if alt => { choose(app, kind, picker, Choice::Link); return }
KeyCode::Char('n') if alt => { choose(app, kind, picker, Choice::New); return }
- // A new harness's folder: M-w starts it in a new worktree of that repository instead.
- KeyCode::Char('w') if alt && matches!(kind, PickerKind::NewFolder { .. }) => { choose(app, kind, picker, Choice::Worktree); return }
KeyCode::Char('i') if alt => { if let PickerKind::Store = kind { return store_install(app, kind, picker) } }
KeyCode::Char(c) if !ctrl && !alt => picker.type_char(c),
_ => {}
@@ -2391,7 +2401,7 @@ fn fzf_key_name(key: &KeyEvent) -> String {
}
#[derive(Clone, Copy, PartialEq, Eq)]
-enum Choice { Enter, Tab, SplitRight, SplitDown, Here, Open, Pause, New, Link, Worktree }
+enum Choice { Enter, Tab, SplitRight, SplitDown, Here, Open, Pause, New, Link }
fn split_key(id: &str) -> Option<(String, String)> {
let (m, a) = id.split_once(':')?;
@@ -2581,12 +2591,7 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {
if choice == Choice::Tab { return project_session(app, &machine, &root) }
if choice == Choice::New {
if app.link(&machine).is_none() { picker.say("That machine is not connected"); return keep(app, kind, picker) }
- load_dsh(app, machine.clone());
- let name = root.rsplit('/').next().unwrap_or(&root).to_string();
- let mut next = Picker::new(format!("new harness · #{name}"), "Claude Code, Codex, a Store harness…");
- let kind = PickerKind::NewWhat { machine, cwd: Some(root) };
- fill(app, &kind, &mut next);
- app.modal = Some(Modal::Picker { kind, picker: next });
+ crate::new_harness::open(app, Some(machine), Some(root));
return;
}
let kind = PickerKind::Open { filter: Filter::All, machine: Some(machine), project: Some(root) };
@@ -2668,48 +2673,6 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {
let label = row.get("name").and_then(|v| v.as_str()).unwrap_or(&dsh).to_string();
create(app, local, What { engine, dsh: Some(dsh), label }, None, None);
}
- PickerKind::NewMachine => { if let Some(machine) = id { new_what(app, machine) } }
- PickerKind::NewWhat { machine, cwd: preset } => {
- let Some(id) = id else { return keep(app, kind, picker) };
- let what = if let Some(engine) = id.strip_prefix("engine:") {
- What { engine: engine.into(), dsh: None, label: theme::engine_label(engine).into() }
- } else {
- let rest = id.trim_start_matches("dsh:");
- let (dsh, engine) = rest.rsplit_once(':').unwrap_or((rest, "claude"));
- let label = picker.current().map(|r| r.label.clone()).unwrap_or_default();
- What { engine: engine.into(), dsh: Some(dsh.into()), label }
- };
- if what.engine == "terminal" { return create(app, machine, what, preset, None) }
- let name = app.fleet.machine_name(&machine);
- // The folder is already known (chosen from `#`): straight to the first message.
- if let Some(cwd) = preset {
- let label = what.label.clone();
- let hint = format!("on {name} in {cwd}");
- return prompt(app, PromptKind::NewMessage { machine, what, cwd: Some(cwd), worktree: false }, &format!("New {label} harness"), "First message (optional) — Enter to start", &hint, "", false);
- }
- let mut next = Picker::new(format!("New {} · folder", what.label), "Search folders…");
- let kind = PickerKind::NewFolder { machine: machine.clone(), what };
- fill(app, &kind, &mut next);
- next.status = name;
- app.modal = Some(Modal::Picker { kind, picker: next });
- }
- PickerKind::NewFolder { machine, what } => {
- let Some(id) = id else { return keep(app, kind, picker) };
- let name = app.fleet.machine_name(&machine);
- match id.as_str() {
- "__path" => prompt(app, PromptKind::NewPath { machine, what }, "Folder", &format!("A folder on {name}"), "~ is that machine's home", "~/", false),
- "__new" => {
- let label = what.label.clone();
- prompt(app, PromptKind::NewMessage { machine, what, cwd: None, worktree: false }, &format!("New {label} harness"), "First message (optional) — Enter to start", &format!("on {name}, in a new project"), "", false)
- }
- cwd => {
- let label = what.label.clone();
- let worktree = choice == Choice::Worktree;
- let hint = if worktree { format!("on {name}: a new worktree of {cwd}, on a branch of its own") } else { format!("on {name} in {cwd}") };
- prompt(app, PromptKind::NewMessage { machine, what, cwd: Some(cwd.to_string()), worktree }, &format!("New {label} harness"), "First message (optional) — Enter to start", &hint, "", false)
- }
- }
- }
PickerKind::Route { text, voice } => {
let Some((machine, agent)) = id.as_deref().and_then(split_key) else { return keep(app, kind, picker) };
if let Some(voice) = voice { return crate::dial::send_spoken(app, &voice, &machine, &agent, &text) }
@@ -2788,16 +2751,6 @@ fn submit_prompt(app: &mut App, p: Prompt) {
});
}
}
- PromptKind::NewPath { machine, what } => {
- if value.is_empty() { return }
- let home = app.homes.get(&machine).cloned().unwrap_or_default();
- let cwd = if value == "~" { home } else if let Some(rest) = value.strip_prefix("~/") { format!("{home}/{rest}") } else { value };
- let label = what.label.clone();
- let name = app.fleet.machine_name(&machine);
- let hint = format!("on {name} in {cwd}");
- prompt(app, PromptKind::NewMessage { machine, what, cwd: Some(cwd), worktree: false }, &format!("New {label} harness"), "First message (optional) — Enter to start", &hint, "", false);
- }
- PromptKind::NewMessage { machine, what, cwd, worktree } => create_in(app, machine, what, cwd, Some(value), worktree),
PromptKind::Send => {
if value.is_empty() { return }
let local = app.fleet.local_id.clone();
@@ -3008,7 +2961,11 @@ fn for_pane(app: &App, pane: u64, key: KeyEvent) -> KeyEvent {
/// What new-harness asks beyond which and where (a script's): made in the background (-d), its
/// name (-n), and what to print once it is there (-P, -F: new-window's).
#[derive(Default, Clone)]
-pub struct NewOpts { pub detached: bool, pub name: Option<String>, pub print: Option<String> }
+pub struct NewOpts {
+ pub detached: bool, pub name: Option<String>, pub print: Option<String>,
+ /// Additional project/permission choices from the interactive draft.
+ pub extra: Option<serde_json::Value>, pub form_id: Option<String>,
+}
/// `new-harness [-dP] [-e engine] [-c folder] [-n name] [-F format] [engine] [@machine] [folder]
/// [task …]`: the engine a known one (else -e's, else Claude Code), the folder a path, and the
diff --git a/tui/src/keys.rs b/tui/src/keys.rs
index edba5e1c9..a3bf3cdfd 100644
--- a/tui/src/keys.rs
+++ b/tui/src/keys.rs
@@ -151,7 +151,7 @@ impl Keymap {
// ── keys tmux leaves unbound: the Harness ones ──
b(ch('C'), "customize-mode -Z", false, "Customize options");
// Harness's own, on keys tmux leaves unbound.
- b(ch('N'), "new-harness", false, "New harness: agent, machine, folder, first message");
+ b(ch('N'), "new-harness", false, "New Harness: agent, project and options");
b(ch('@'), "choose-tree -m", false, "Machines (then their harnesses)");
b(ch('T'), "new-terminal", false, "New terminal (a shell) beside this pane");
b(ch('a'), "next-harness", false, "Go to the next harness that needs you");
diff --git a/tui/src/main.rs b/tui/src/main.rs
index 11a479b62..56f01ddc3 100644
--- a/tui/src/main.rs
+++ b/tui/src/main.rs
@@ -31,6 +31,7 @@ mod input;
mod layout;
mod local;
mod modal;
+mod new_harness;
mod mouse;
mod options;
mod paste;
diff --git a/tui/src/modal.rs b/tui/src/modal.rs
index d330b39cc..b4a906a92 100644
--- a/tui/src/modal.rs
+++ b/tui/src/modal.rs
@@ -1,6 +1,5 @@
//! The overlays and what their rows are: the fzf list's modes (harnesses, > commands, @ machines,
-//! # projects, : models, * store, ? help), needs input, new harness (machine → agent → folder →
-//! first message), layouts, and the
+//! # projects, : models, * store, ? help), needs input, the New Harness form, layouts, and the
//! one-line prompts (rename, first message, send, link password).
use ratatui::style::Style;
@@ -45,9 +44,6 @@ pub enum PickerKind {
Layout,
Help,
Store,
- NewMachine,
- NewWhat { machine: String, cwd: Option<String> },
- NewFolder { machine: String, what: What },
/// A task routed to a harness; [voice]: the dial's spoken task it answers.
Route { text: String, voice: Option<String> },
/// `show-messages`, `list-keys`, `choose-buffer`.
@@ -62,8 +58,6 @@ pub enum PickerKind {
pub enum PromptKind {
RenameTab,
RenameHarness { machine: String, agent: String },
- NewPath { machine: String, what: What },
- NewMessage { machine: String, what: What, cwd: Option<String>, worktree: bool },
Send,
Broadcast,
LinkPassword { machine: String },
@@ -146,6 +140,8 @@ pub struct Complete { pub prompt: Prompt, pub list: Vec<String>, pub flag: Optio
pub enum Modal {
/// tmux's display-menu: a box of items, each with its key; Enter or the key runs one.
Menu(Menu),
+ /// Compact New Harness form with searchable choices and a persistent draft.
+ NewHarness(Box<crate::new_harness::Form>),
Picker { kind: PickerKind, picker: Picker },
Prompt(Prompt),
/// tmux `confirm-before`: `Confirm 'kill-pane'? (y/n)` in the status line; `key` answers
@@ -560,27 +556,6 @@ pub fn new_what_rows(catalog: &[Value]) -> Vec<Row> {
rows
}
-pub fn new_folder_rows(app: &App, machine: &str) -> Vec<Row> {
- let home = app.homes.get(machine).cloned().unwrap_or_default();
- let tilde = |p: &str| if !home.is_empty() && p.starts_with(&home) { format!("~{}", &p[home.len()..]) } else { p.to_string() };
- let mut rows = vec![
- Row::new("__new", "+ New project").group("Start").detail(vec![span(format!("{}/harnesses/<name>", tilde(&home)), fg(theme::MUTED))]),
- Row::new("__path", "… Type a path").group("Start").detail(vec![span("any folder on that machine", fg(theme::MUTED))]),
- ];
- let mut agents: Vec<_> = app.fleet.agents.values().filter(|a| a.machine_id == machine && !a.cwd.is_empty()).collect();
- agents.sort_by_key(|a| std::cmp::Reverse(a.created_at));
- let mut seen = Vec::new();
- for a in agents {
- if seen.contains(&a.cwd) || seen.len() >= 40 { continue }
- seen.push(a.cwd.clone());
- let short = tilde(&a.cwd);
- let leaf = short.rsplit('/').next().unwrap_or(&short).to_string();
- rows.push(Row::new(a.cwd.clone(), leaf).extra(short.clone()).group("Recent folders").detail(vec![span(short, fg(theme::MUTED))]));
- }
- if !home.is_empty() { rows.push(Row::new(home.clone(), "~").group("Recent folders").detail(vec![span("home folder", fg(theme::MUTED))])) }
- rows
-}
-
pub fn store_rows(catalog: &[Value]) -> Vec<Row> {
catalog.iter().filter(|r| r.get("kind").and_then(Value::as_str) != Some("viewer")).filter_map(|row| {
let id = row.get("id")?.as_str()?;
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
new file mode 100644
index 000000000..c967916df
--- /dev/null
+++ b/tui/src/new_harness.rs
@@ -0,0 +1,1779 @@
+//! The desktop's compact New Harness form, with a persistent draft and side choosers.
+mod data;
+mod receipt;
+pub(crate) use receipt::Creation;
+mod view;
+use crate::{
+ app::App,
+ modal::{self, Modal, What},
+ picker::{Picker, Row},
+ theme,
+};
+use crossterm::event::{
+ KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
+};
+use ratatui::{
+ buffer::Buffer,
+ layout::{Position, Rect},
+ style::{Color, Modifier, Style},
+ widgets::{Block, BorderType, Borders, Widget},
+};
+use serde_json::{Value, json};
+use std::{collections::HashMap, time::Duration};
+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
+pub use view::draw;
+
+#[derive(Clone, Debug)]
+pub enum Project {
+ Folder(String),
+ New(String),
+ Clone(String),
+}
+#[derive(Clone, Debug)]
+pub struct Draft {
+ pub machine: String,
+ pub what: What,
+ pub project: Project,
+ pub permission: String,
+ pub worktree: Option<bool>,
+ pub branch: Option<String>,
+ pub new_branch: Option<String>,
+ /// Model route and profile are explicit choices; never silently replace either at launch.
+ pub model: Option<(String, String, String)>,
+ pub profile: Option<(String, String, String)>,
+}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Field {
+ Agent,
+ Project,
+ Options,
+ Model,
+ Approvals,
+ Profile,
+ Branch,
+ Worktree,
+ Create,
+}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ProjectAction {
+ Open,
+ New,
+ Clone,
+}
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum Choice {
+ Agent,
+ Compatible(String),
+ Project,
+ Machine(ProjectAction),
+ Approvals,
+ Model,
+ Profile,
+ Branch,
+ Folder(String),
+ Path,
+ Clone,
+ NewFolder,
+}
+impl Choice {
+ fn editing(&self) -> bool {
+ matches!(self, Self::Path | Self::Clone | Self::NewFolder)
+ }
+}
+struct Child {
+ kind: Choice,
+ picker: Picker,
+ generation: String,
+}
+
+pub struct Form {
+ pub draft: Draft,
+ pub id: String,
+ pub starting: bool,
+ checking: bool,
+ pub error: String,
+ pub attempt: Option<Creation>,
+ prepared_folder: Option<String>,
+ focus: Field,
+ expanded: bool,
+ child: Option<Child>,
+ child_active: bool,
+ trail: Vec<Child>,
+ area: Rect,
+ child_area: Rect,
+ hits: Vec<(Rect, Field)>,
+ machine_label: String,
+ home: String,
+ git: Value,
+ git_key: Option<(String, String)>,
+ git_loading: bool,
+ git_generation: String,
+ models: Value,
+ profiles: Value,
+ resource_generation: String,
+ projects: HashMap<String, Project>,
+ modes: HashMap<String, String>,
+}
+impl Form {
+ fn project_payload(&self) -> Result<(Option<String>, Value), String> {
+ // A confirmed failure may have already made a clone or worktree. Reuse that
+ // exact folder until the user explicitly chooses another project/branch.
+ if let Some(path) = &self.prepared_folder {
+ if matches!(&self.draft.project, Project::Folder(p) if p == path)
+ && self.draft.worktree == Some(false)
+ && self.draft.branch.is_none()
+ && self.draft.new_branch.is_none()
+ {
+ return Ok((Some(path.clone()), json!({})));
+ }
+ }
+ data::project_payload(&self.draft, &self.git)
+ }
+ fn fields(&self) -> Vec<Field> {
+ let mut fields = vec![Field::Agent, Field::Project, Field::Options];
+ if self.expanded {
+ if self.draft.what.engine != "terminal" {
+ fields.push(Field::Model);
+ }
+ if !data::modes(&self.draft.what.engine).is_empty() {
+ fields.push(Field::Approvals);
+ }
+ if self.draft.what.engine == "codex" && self.draft.model.is_none() {
+ fields.push(Field::Profile);
+ }
+ fields.extend([Field::Branch, Field::Worktree]);
+ }
+ fields.push(Field::Create);
+ fields
+ }
+ fn move_by(&mut self, delta: isize) {
+ let fields = self.fields();
+ let at = fields.iter().position(|f| *f == self.focus).unwrap_or(0) as isize;
+ self.focus = fields[(at + delta).rem_euclid(fields.len() as isize) as usize];
+ }
+ fn worktree(&self) -> bool {
+ self.draft.what.engine != "terminal"
+ && data::git(&self.git)
+ && self.draft.worktree.unwrap_or(true)
+ }
+ fn blocked(&self, field: Field) -> Option<&str> {
+ if matches!(field, Field::Branch | Field::Worktree) {
+ if self.git_loading {
+ Some("Checking Git…")
+ } else if self.git["error"].is_string() {
+ Some("Could not read Git · Enter to retry")
+ } else if !data::git(&self.git) || self.draft.what.engine == "terminal" {
+ Some("Not a Git repository")
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ }
+ fn project_label(&self) -> String {
+ let value = match &self.draft.project {
+ Project::Folder(p) => short_path(p, &self.home),
+ Project::New(n) => {
+ if n.is_empty() {
+ "New Folder".into()
+ } else {
+ format!("New Folder: {n}")
+ }
+ }
+ Project::Clone(url) => format!("Clone: {url}"),
+ };
+ format!("{}:{value}", self.machine_label)
+ }
+ fn describe(&self, field: Field) -> (&str, String) {
+ let (label, value) = match field {
+ Field::Agent => (
+ if self.draft.what.dsh.is_some() {
+ "Harness"
+ } else {
+ "Agent"
+ },
+ self.draft.what.label.clone(),
+ ),
+ Field::Project => ("Project", self.project_label()),
+ Field::Options => ("Options", if self.expanded { "[-]" } else { "[+]" }.into()),
+ Field::Model => (
+ "Model",
+ self.draft
+ .model
+ .as_ref()
+ .map(|(_, id, node)| {
+ if node.is_empty() {
+ id.clone()
+ } else {
+ format!("{id} · {node}")
+ }
+ })
+ .unwrap_or_else(|| data::subscription(&self.draft.what.engine).into()),
+ ),
+ Field::Approvals => (
+ "Approvals",
+ data::mode_label(&self.draft.what.engine, &self.draft.permission),
+ ),
+ Field::Profile => (
+ "Profile",
+ self.draft
+ .profile
+ .as_ref()
+ .map(|(_, _, n)| n.clone())
+ .unwrap_or_else(|| "Default".into()),
+ ),
+ Field::Branch => (
+ "Branch",
+ self.draft
+ .new_branch
+ .as_ref()
+ .map(|n| format!("{n} · new"))
+ .or_else(|| {
+ data::branch_ref(&self.draft, &self.git)
+ .map(|r| data::branch_name(&r).into())
+ })
+ .unwrap_or_else(|| {
+ if self.worktree() {
+ "Choose a branch"
+ } else {
+ "Detached HEAD"
+ }
+ .into()
+ }),
+ ),
+ Field::Worktree => (
+ "Worktree",
+ if self.worktree() { "[x]" } else { "[ ]" }.into(),
+ ),
+ Field::Create => (
+ if self.starting {
+ if self.checking {
+ "Checking…"
+ } else {
+ "Starting…"
+ }
+ } else if self.attempt.is_some() {
+ "Check status"
+ } else {
+ "New Harness"
+ },
+ String::new(),
+ ),
+ };
+ (
+ label,
+ self.blocked(field).map(str::to_string).unwrap_or(value),
+ )
+ }
+}
+fn short_path(path: &str, home: &str) -> String {
+ if !home.is_empty() && (path == home || path.starts_with(&format!("{home}/"))) {
+ format!("~{}", &path[home.len()..])
+ } else {
+ path.into()
+ }
+}
+fn defaults_path() -> std::path::PathBuf {
+ std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default())
+ .join(".harness/tui/new-harness.json")
+}
+fn defaults() -> Value {
+ if cfg!(test) {
+ return Value::Null;
+ }
+ std::fs::read(defaults_path())
+ .ok()
+ .and_then(|s| serde_json::from_slice(&s).ok())
+ .unwrap_or(Value::Null)
+}
+fn remember(form: &Form) {
+ use std::{io::Write, os::unix::fs::OpenOptionsExt};
+ let path = defaults_path();
+ let Some(parent) = path.parent() else { return };
+ let mut saved = defaults();
+ if !saved.is_object() {
+ saved = json!({});
+ }
+ let d = &form.draft;
+ if !saved["permissions"].is_object() {
+ saved["permissions"] = json!({});
+ }
+ saved["permissions"][&d.what.engine] = json!(d.permission);
+ saved["engine"] = json!(d.what.engine);
+ saved["dsh"] = json!(d.what.dsh);
+ saved["label"] = json!(d.what.label);
+ if !saved["projects"].is_object() {
+ saved["projects"] = json!({});
+ }
+ if let Project::Folder(p) = &d.project {
+ saved["projects"][&d.machine] = json!(p);
+ }
+ let tmp = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
+ let write = || -> std::io::Result<()> {
+ std::fs::create_dir_all(parent)?;
+ let mut f = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&tmp)?;
+ f.write_all(saved.to_string().as_bytes())?;
+ std::fs::rename(&tmp, &path)
+ };
+ if write().is_err() {
+ let _ = std::fs::remove_file(tmp);
+ }
+}
+
+pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
+ if machine
+ .as_ref()
+ .is_some_and(|id| !app.fleet.machines.iter().any(|m| m.id == *id && m.usable()))
+ {
+ return app.error("That machine is not connected");
+ }
+ if app
+ .new_harness_draft
+ .as_ref()
+ .is_some_and(|f| f.starting || f.attempt.is_some())
+ || (machine.is_none() && cwd.is_none() && app.new_harness_draft.is_some())
+ {
+ let mut form = app.new_harness_draft.take().unwrap();
+ refresh_form(app, &mut form);
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ }
+ let saved = defaults();
+ let machine = machine
+ .filter(|id| app.fleet.machines.iter().any(|m| m.id == *id && m.usable()))
+ .or_else(|| {
+ app.fleet
+ .machines
+ .iter()
+ .find(|m| m.local && m.usable())
+ .map(|m| m.id.clone())
+ })
+ .or_else(|| {
+ app.fleet
+ .machines
+ .iter()
+ .find(|m| m.usable())
+ .map(|m| m.id.clone())
+ });
+ let Some(machine) = machine else {
+ return app.error("No machine is connected yet");
+ };
+ let current = app
+ .focused()
+ .and_then(|f| app.panes.get(&f))
+ .filter(|p| p.machine_id == machine)
+ .and_then(|p| app.fleet.agent(&p.machine_id, &p.agent_id));
+ let engine = saved["engine"]
+ .as_str()
+ .unwrap_or_else(|| current.map(|a| a.engine.as_str()).unwrap_or("codex"))
+ .to_string();
+ let what = What {
+ label: saved["label"]
+ .as_str()
+ .unwrap_or(theme::engine_label(&engine))
+ .into(),
+ engine: engine.clone(),
+ dsh: saved["dsh"].as_str().map(str::to_string),
+ };
+ 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()));
+ let permission = saved["permissions"][&engine]
+ .as_str()
+ .map(str::to_string)
+ .or_else(|| app.options.get("@hn-permission-mode", "", None))
+ .filter(|p| data::modes(&engine).iter().any(|(id, _)| id == p))
+ .unwrap_or_else(|| "auto".into());
+ let draft = Draft {
+ machine: machine.clone(),
+ what,
+ project,
+ permission,
+ worktree: None,
+ branch: None,
+ new_branch: None,
+ model: None,
+ profile: None,
+ };
+ let mut form = Box::new(Form {
+ draft,
+ id: uuid::Uuid::new_v4().to_string(),
+ starting: false,
+ checking: false,
+ error: String::new(),
+ attempt: None,
+ prepared_folder: None,
+ focus: Field::Create,
+ expanded: false,
+ child: None,
+ child_active: false,
+ trail: vec![],
+ area: Rect::default(),
+ child_area: Rect::default(),
+ hits: vec![],
+ machine_label: String::new(),
+ home: String::new(),
+ git: Value::Null,
+ git_key: None,
+ git_loading: false,
+ git_generation: String::new(),
+ models: Value::Null,
+ profiles: Value::Null,
+ resource_generation: String::new(),
+ projects: HashMap::new(),
+ modes: HashMap::new(),
+ });
+ refresh_form(app, &mut form);
+ sync_git(app, &mut form, false);
+ app.modal = Some(Modal::NewHarness(form));
+ crate::input::load_dsh(app, machine);
+}
+fn refresh_form(app: &App, form: &mut Form) {
+ form.machine_label = app.fleet.machine_name(&form.draft.machine).to_string();
+ form.home = app
+ .homes
+ .get(&form.draft.machine)
+ .cloned()
+ .unwrap_or_default();
+ if form.draft.what.engine == "terminal"
+ && matches!(&form.draft.project,Project::Folder(p) if p.is_empty())
+ && !form.home.is_empty()
+ {
+ form.draft.project = Project::Folder(form.home.clone());
+ }
+ if let Some(dsh) = &form.draft.what.dsh {
+ if let Some(row) = app
+ .dsh
+ .get(&form.draft.machine)
+ .into_iter()
+ .flatten()
+ .find(|r| r["id"].as_str() == Some(dsh))
+ {
+ if let Some(name) = row["name"].as_str() {
+ form.draft.what.label =
+ format!("{name} · {}", theme::engine_label(&form.draft.what.engine));
+ }
+ }
+ }
+ let Some(c) = &mut form.child else { return };
+ let rows = match &c.kind {
+ Choice::Agent => Some(agent_rows(app, &form.draft.machine)),
+ Choice::Compatible(dsh) => Some(compatible_rows(app, &form.draft.machine, dsh)),
+ Choice::Project => Some(project_rows(app, &form.draft)),
+ Choice::Machine(_) => Some(modal::new_machine_rows(app, &app.fleet.local_id)),
+ Choice::Approvals => Some(
+ data::modes(&form.draft.what.engine)
+ .iter()
+ .map(|(id, label)| Row::new(*id, *label))
+ .collect(),
+ ),
+ Choice::Model => Some(data::model_rows(&form.models, &form.draft.what.engine)),
+ Choice::Profile => {
+ let mut rows = vec![Row::new("default", "Default")];
+ for p in form.profiles["profiles"].as_array().into_iter().flatten() {
+ if let Some(path) = p["path"].as_str() {
+ rows.push(Row::new(path, p["label"].as_str().unwrap_or(path)).extra(path));
+ }
+ }
+ Some(rows)
+ }
+ Choice::Branch => Some(data::branch_rows(
+ &form.git,
+ form.draft.worktree.unwrap_or(data::git(&form.git)),
+ &c.picker.query,
+ )),
+ _ => None,
+ };
+ if let Some(rows) = rows {
+ c.picker.set_rows(rows);
+ }
+}
+pub fn refresh(app: &mut App) {
+ if !matches!(app.modal, Some(Modal::NewHarness(_))) {
+ return;
+ }
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
+ return;
+ };
+ refresh_form(app, &mut form);
+ sync_git(app, &mut form, false);
+ app.modal = Some(Modal::NewHarness(form));
+}
+fn agent_rows(app: &App, machine: &str) -> Vec<Row> {
+ modal::new_what_rows(app.dsh.get(machine).map(Vec::as_slice).unwrap_or(&[]))
+}
+fn compatible_rows(app: &App, machine: &str, dsh: &str) -> Vec<Row> {
+ let row = app
+ .dsh
+ .get(machine)
+ .into_iter()
+ .flatten()
+ .find(|r| r["id"].as_str() == Some(dsh));
+ let engines: Vec<_> = row
+ .and_then(|r| r["engines"].as_array())
+ .map(|a| a.iter().filter_map(Value::as_str).collect())
+ .filter(|a: &Vec<&str>| !a.is_empty())
+ .unwrap_or_else(|| vec![row.and_then(|r| r["engine"].as_str()).unwrap_or("claude")]);
+ engines
+ .into_iter()
+ .map(|e| Row::new(format!("engine:{e}"), theme::engine_label(e)))
+ .collect()
+}
+fn project_rows(app: &App, draft: &Draft) -> Vec<Row> {
+ let mut rows = vec![];
+ if draft.what.engine != "terminal" {
+ rows.push(Row::new("clone", "Clone Repository"));
+ }
+ rows.push(Row::new("folder", "Open Folder"));
+ if draft.what.engine != "terminal" {
+ rows.push(Row::new("new", "New Folder"));
+ }
+ let mut agents: Vec<_> = app
+ .fleet
+ .agents
+ .values()
+ .filter(|a| !a.cwd.is_empty())
+ .collect();
+ agents.sort_by_key(|a| {
+ (
+ a.machine_id != app.fleet.local_id,
+ std::cmp::Reverse(a.recency()),
+ )
+ });
+ let mut seen = std::collections::HashSet::new();
+ for a in agents {
+ if !seen.insert((a.machine_id.clone(), a.cwd.clone())) {
+ continue;
+ }
+ let short = short_path(
+ &a.cwd,
+ app.homes
+ .get(&a.machine_id)
+ .map(String::as_str)
+ .unwrap_or(""),
+ );
+ let mut row = Row::new(
+ format!("at:{}\t{}", a.machine_id, a.cwd),
+ format!("{}:{short}", app.fleet.machine_name(&a.machine_id)),
+ )
+ .group("Recent projects");
+ row.disabled = !app
+ .fleet
+ .machines
+ .iter()
+ .any(|m| m.id == a.machine_id && m.usable());
+ if row.disabled {
+ row.label.push_str(" · offline");
+ }
+ rows.push(row);
+ if seen.len() == 60 {
+ break;
+ }
+ }
+ rows
+}
+fn sync_git(app: &mut App, form: &mut Form, force: bool) {
+ let path = if let Project::Folder(p) = &form.draft.project {
+ Some(p.clone())
+ } else {
+ None
+ };
+ if form.draft.what.engine == "terminal" || path.is_none() {
+ form.git = Value::Null;
+ form.git_key = None;
+ form.git_loading = false;
+ form.git_generation.clear();
+ return;
+ }
+ let path = path.unwrap();
+ let key = (form.draft.machine.clone(), path.clone());
+ if !force && form.git_key.as_ref() == Some(&key) {
+ return;
+ }
+ let Some(link) = app.link(&form.draft.machine) else {
+ form.git = json!({"error":"OFFLINE"});
+ return;
+ };
+ form.git_key = Some(key.clone());
+ form.git_loading = true;
+ form.git = Value::Null;
+ form.git_generation = uuid::Uuid::new_v4().to_string();
+ let generation = form.git_generation.clone();
+ let id = form.id.clone();
+ app.spawn(
+ async move {
+ link.rpc(
+ "git_project_info",
+ json!({"path":path}),
+ Duration::from_secs(20),
+ )
+ .await
+ },
+ move |app, reply| {
+ with_form(app, &id, |app, form| {
+ if form.git_generation != generation {
+ return;
+ }
+ form.git_loading = false;
+ form.git = reply.unwrap_or_else(|_| json!({"error":"UNAVAILABLE"}));
+ if let Some(main) = form.git["mainFolder"].as_str().map(str::to_string)
+ .filter(|_| !matches!(&form.draft.project, Project::Folder(p) if form.prepared_folder.as_ref() == Some(p)))
+ {
+ if form.draft.worktree == Some(false) && form.draft.branch.is_none() {
+ form.draft.branch = form.git["branch"]
+ .as_str()
+ .map(|b| format!("refs/heads/{b}"));
+ }
+ form.draft.project = Project::Folder(main.clone());
+ form.git_key = Some((form.draft.machine.clone(), main));
+ form.git["branch"] = form.git["mainBranch"].clone();
+ }
+ refresh_form(app, form);
+ });
+ },
+ );
+}
+fn with_form(app: &mut App, id: &str, f: impl FnOnce(&mut App, &mut Form)) {
+ if matches!(&app.modal,Some(Modal::NewHarness(form)) if form.id==id) {
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
+ return;
+ };
+ f(app, &mut form);
+ app.modal = Some(Modal::NewHarness(form));
+ } else if app
+ .new_harness_draft
+ .as_ref()
+ .is_some_and(|form| form.id == id)
+ {
+ let mut form = app.new_harness_draft.take().unwrap();
+ f(app, &mut form);
+ app.new_harness_draft = Some(form);
+ }
+}
+fn load_resource(app: &mut App, form: &mut Form, models: bool) {
+ let Some(link) = app.link(&form.draft.machine) else {
+ return;
+ };
+ let id = form.id.clone();
+ let generation = uuid::Uuid::new_v4().to_string();
+ form.resource_generation = generation.clone();
+ if let Some(c) = &mut form.child {
+ c.picker.busy = Some("Loading…".into());
+ }
+ app.spawn(
+ async move {
+ link.rpc(
+ if models {
+ "grid_models_list"
+ } else {
+ "codex_profiles_list"
+ },
+ json!({"rowState":true}),
+ Duration::from_secs(30),
+ )
+ .await
+ },
+ move |app, reply| {
+ with_form(app, &id, |app, form| {
+ if form.resource_generation != generation {
+ return;
+ }
+ let value = reply.unwrap_or_else(|_| json!({"error":"UNAVAILABLE"}));
+ if value["error"].is_string() {
+ form.error = if models {
+ "Could not load models · choose Refresh models"
+ } else {
+ "Could not load profiles · reopen Profile to retry"
+ }
+ .into();
+ }
+ if models {
+ form.models = value
+ } else {
+ form.profiles = value
+ }
+ if let Some(c) = &mut form.child {
+ c.picker.busy = None;
+ }
+ refresh_form(app, form);
+ });
+ },
+ );
+}
+fn child(app: &mut App, form: &mut Form, kind: Choice, initial: &str) {
+ let hint = match &kind {
+ Choice::Agent => "Search agents and harnesses",
+ Choice::Compatible(_) => "Choose a coding agent",
+ Choice::Project => "Search projects",
+ Choice::Machine(_) => "Choose a machine",
+ Choice::Approvals => "Search approvals",
+ Choice::Model => "Search models",
+ Choice::Profile => "Search profiles",
+ Choice::Branch => "Search or create a branch",
+ Choice::Folder(_) => "Search folders · Ctrl-L path",
+ Choice::Path => "/path/to/project or ~/project",
+ Choice::Clone => "GitHub URL or owner/repository",
+ Choice::NewFolder => "Folder name (optional)",
+ };
+ let mut picker = Picker::new("", hint);
+ picker.keep_order = true;
+ picker.query = initial.into();
+ picker.qcursor = initial.chars().count();
+ picker.empty = "No matches".into();
+ form.child = Some(Child {
+ kind: kind.clone(),
+ picker,
+ generation: uuid::Uuid::new_v4().to_string(),
+ });
+ refresh_form(app, form);
+ let selected = match &kind {
+ Choice::Agent => Some(
+ form.draft
+ .what
+ .dsh
+ .as_ref()
+ .map(|d| format!("dsh:{d}:{}", form.draft.what.engine))
+ .unwrap_or_else(|| format!("engine:{}", form.draft.what.engine)),
+ ),
+ Choice::Compatible(_) => Some(format!("engine:{}", form.draft.what.engine)),
+ Choice::Project => {
+ if let Project::Folder(p) = &form.draft.project {
+ Some(format!("at:{}\t{p}", form.draft.machine))
+ } else {
+ None
+ }
+ }
+ Choice::Machine(_) => Some(app.fleet.local_id.clone()),
+ Choice::Approvals => Some(form.draft.permission.clone()),
+ Choice::Model => Some(
+ form.draft
+ .model
+ .as_ref()
+ .map(|(grid, id, _)| json!([grid, id]).to_string())
+ .unwrap_or_else(|| "subscription".into()),
+ ),
+ Choice::Profile => Some(
+ form.draft
+ .profile
+ .as_ref()
+ .map(|(_, p, _)| p.clone())
+ .unwrap_or_else(|| "default".into()),
+ ),
+ Choice::Branch => data::branch_ref(&form.draft, &form.git),
+ _ => None,
+ };
+ if let (Some(c), Some(id)) = (&mut form.child, selected) {
+ c.picker.select(&id);
+ }
+ match kind {
+ Choice::Folder(path) => load_folder(app, form, path),
+ Choice::Model => load_resource(app, form, true),
+ Choice::Profile => load_resource(app, form, false),
+ _ => {}
+ }
+}
+fn load_folder(app: &mut App, form: &mut Form, path: String) {
+ let Some(link) = app.link(&form.draft.machine) else {
+ form.error = "That machine is not connected".into();
+ return;
+ };
+ let id = form.id.clone();
+ let Some(c) = &mut form.child else { return };
+ let generation = c.generation.clone();
+ c.picker.busy = Some("Loading folders…".into());
+ app.spawn(
+ async move {
+ link.rpc("fs_list_dir", json!({"path":path}), Duration::from_secs(20))
+ .await
+ },
+ move |app, reply| {
+ with_form(app, &id, |_, form| {
+ let Some(c) = &mut form.child else { return };
+ if c.generation != generation {
+ return;
+ }
+ c.picker.busy = None;
+ match reply {
+ Ok(v) if v["path"].is_string() => {
+ let path = v["path"].as_str().unwrap().to_string();
+ c.kind = Choice::Folder(path.clone());
+ c.picker.placeholder =
+ format!("{} · Ctrl-L path", short_path(&path, &form.home));
+ let mut rows = vec![Row::new("use", "Use this folder")];
+ if path != "/" {
+ rows.push(Row::new("up", ".. /"));
+ }
+ for entry in v["entries"].as_array().into_iter().flatten() {
+ if entry["isDir"] == false {
+ continue;
+ }
+ if let Some(name) = entry["name"]
+ .as_str()
+ .filter(|n| !n.contains('/') && *n != "." && *n != "..")
+ {
+ rows.push(Row::new(format!("dir:{name}"), format!("{name}/")));
+ }
+ }
+ c.picker.set_rows(rows);
+ }
+ _ => c.picker.empty = "Could not open folder · Ctrl-L to edit path".into(),
+ }
+ });
+ },
+ );
+}
+fn reveal(app: &mut App, form: &mut Form) {
+ form.child = None;
+ form.child_active = false;
+ form.trail.clear();
+ if form.blocked(form.focus).is_some() {
+ return;
+ }
+ let kind = match form.focus {
+ Field::Agent => Choice::Agent,
+ Field::Project => Choice::Project,
+ Field::Model => Choice::Model,
+ Field::Approvals => Choice::Approvals,
+ Field::Profile => Choice::Profile,
+ Field::Branch => Choice::Branch,
+ _ => return,
+ };
+ child(app, form, kind, "");
+}
+fn activate(app: &mut App, form: &mut Form) -> bool {
+ form.error.clear();
+ if form.blocked(form.focus).is_some() {
+ if form.git["error"].is_string() {
+ sync_git(app, form, true);
+ }
+ return false;
+ }
+ match form.focus {
+ Field::Create => return true,
+ Field::Options => {
+ form.expanded = !form.expanded;
+ form.child = None;
+ }
+ Field::Worktree => {
+ form.draft.worktree = Some(!form.worktree());
+ form.draft.branch = None;
+ form.draft.new_branch = None;
+ }
+ _ => {
+ if form.child.is_none() {
+ reveal(app, form);
+ }
+ form.child_active = true;
+ }
+ }
+ false
+}
+fn set_project(form: &mut Form, project: Project) {
+ form.prepared_folder = None;
+ form.draft.project = project;
+ form.draft.worktree = None;
+ form.draft.branch = None;
+ form.draft.new_branch = None;
+ form.git_key = None;
+}
+fn set_machine(app: &mut App, form: &mut Form, machine: &str) {
+ if form.draft.machine == machine {
+ return;
+ }
+ form.projects
+ .insert(form.draft.machine.clone(), form.draft.project.clone());
+ form.draft.machine = machine.into();
+ let project = form.projects.get(machine).cloned().unwrap_or_else(|| {
+ if form.draft.what.engine == "terminal" {
+ Project::Folder(app.homes.get(machine).cloned().unwrap_or_default())
+ } else {
+ Project::New(String::new())
+ }
+ });
+ set_project(form, project);
+ form.models = Value::Null;
+ form.profiles = Value::Null;
+ form.resource_generation.clear();
+ crate::input::load_dsh(app, machine.into());
+ refresh_form(app, form);
+}
+fn set_engine(form: &mut Form, engine: &str) {
+ form.modes.insert(
+ form.draft.what.engine.clone(),
+ form.draft.permission.clone(),
+ );
+ form.draft.what.engine = engine.into();
+ form.draft.permission = form
+ .modes
+ .get(engine)
+ .filter(|p| data::modes(engine).iter().any(|(id, _)| id == p))
+ .cloned()
+ .unwrap_or_else(|| "auto".into());
+ if engine == "terminal" {
+ form.draft.model = None;
+ form.draft.profile = None;
+ form.draft.worktree = Some(false);
+ if !matches!(form.draft.project, Project::Folder(_)) {
+ form.draft.project = Project::Folder(form.home.clone());
+ }
+ }
+ form.git_key = None;
+}
+fn step_into(app: &mut App, form: &mut Form, previous: Child, kind: Choice, initial: &str) {
+ form.trail.push(previous);
+ child(app, form, kind, initial);
+ form.child_active = true;
+}
+fn choose(app: &mut App, form: &mut Form) {
+ let Some(c) = form.child.take() else { return };
+ let query = c.picker.query.trim().to_string();
+ let id = c.picker.current_id().unwrap_or_default();
+ if !c.kind.editing() && (id.is_empty() || c.picker.current().is_some_and(|r| r.disabled)) {
+ form.child = Some(c);
+ return;
+ }
+ match &c.kind {
+ Choice::Agent | Choice::Compatible(_) => {
+ if let Some((dsh, _)) = id.strip_prefix("dsh:").and_then(|s| s.rsplit_once(':')) {
+ let dsh = dsh.to_string();
+ step_into(app, form, c, Choice::Compatible(dsh), "");
+ return;
+ }
+ let Some(engine) = id.strip_prefix("engine:") else {
+ form.child = Some(c);
+ return;
+ };
+ let dsh = if let Choice::Compatible(dsh) = &c.kind {
+ Some(dsh.clone())
+ } else {
+ None
+ };
+ set_engine(form, engine);
+ form.draft.what.dsh = dsh;
+ form.draft.what.label = theme::engine_label(engine).into();
+ }
+ Choice::Project => match id.as_str() {
+ "clone" | "new" | "folder" => {
+ let action = match id.as_str() {
+ "clone" => ProjectAction::Clone,
+ "new" => ProjectAction::New,
+ _ => ProjectAction::Open,
+ };
+ step_into(app, form, c, Choice::Machine(action), "");
+ return;
+ }
+ _ => {
+ if let Some((machine, path)) =
+ id.strip_prefix("at:").and_then(|s| s.split_once('\t'))
+ {
+ set_machine(app, form, machine);
+ set_project(form, Project::Folder(path.into()));
+ } else {
+ form.child = Some(c);
+ return;
+ }
+ }
+ },
+ Choice::Machine(action) => {
+ let action = *action;
+ set_machine(app, form, &id);
+ let next = match action {
+ ProjectAction::Clone => Choice::Clone,
+ ProjectAction::New => Choice::NewFolder,
+ ProjectAction::Open => {
+ Choice::Folder(if let Project::Folder(p) = &form.draft.project {
+ p.clone()
+ } else {
+ form.home.clone()
+ })
+ }
+ };
+ step_into(app, form, c, next, "");
+ return;
+ }
+ Choice::Approvals => form.draft.permission = id,
+ Choice::Model => {
+ if id == "refresh" {
+ form.child = Some(c);
+ load_resource(app, form, true);
+ return;
+ } else if id == "subscription" {
+ form.draft.model = None
+ } else if let Ok(pair) = serde_json::from_str::<Vec<String>>(&id) {
+ if pair.len() != 2 {
+ form.child = Some(c);
+ return;
+ }
+ let node = form.models["grids"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .find(|g| g["name"].as_str() == Some(&pair[0]))
+ .and_then(|g| g["models"].as_array())
+ .into_iter()
+ .flatten()
+ .find(|m| m["id"].as_str() == Some(&pair[1]))
+ .and_then(|m| m["node"].as_str())
+ .unwrap_or("")
+ .to_string();
+ form.draft.model = Some((pair[0].clone(), pair[1].clone(), node));
+ } else {
+ form.child = Some(c);
+ return;
+ }
+ }
+ Choice::Profile => {
+ form.draft.profile = if id == "default" {
+ None
+ } else {
+ Some((
+ form.draft.machine.clone(),
+ id,
+ c.picker.current().unwrap().label.clone(),
+ ))
+ }
+ }
+ Choice::Branch => {
+ if let Some(name) = id.strip_prefix("new:") {
+ form.draft.new_branch = Some(name.into());
+ } else {
+ form.draft.branch = Some(id);
+ form.draft.new_branch = None;
+ }
+ }
+ Choice::Folder(path) => match id.as_str() {
+ "use" => set_project(form, Project::Folder(path.clone())),
+ "up" => {
+ let parent = path
+ .rsplit_once('/')
+ .map(|(p, _)| if p.is_empty() { "/" } else { p })
+ .unwrap_or("/")
+ .to_string();
+ step_into(app, form, c, Choice::Folder(parent), "");
+ return;
+ }
+ _ => {
+ if let Some(name) = id.strip_prefix("dir:") {
+ let next = format!("{}/{name}", path.trim_end_matches('/'));
+ step_into(app, form, c, Choice::Folder(next), "");
+ return;
+ } else {
+ form.child = Some(c);
+ return;
+ }
+ }
+ },
+ Choice::Path => {
+ if query.starts_with('~') && form.home.is_empty() {
+ form.error = "Home is loading; enter an absolute path".into();
+ form.child = Some(c);
+ return;
+ }
+ let path = if query == "~" {
+ form.home.clone()
+ } else if let Some(rest) = query.strip_prefix("~/") {
+ format!("{}/{rest}", form.home)
+ } else {
+ query
+ };
+ if !path.starts_with('/') {
+ form.error = "Enter an absolute path or ~/folder".into();
+ form.child = Some(c);
+ return;
+ }
+ step_into(app, form, c, Choice::Folder(path), "");
+ return;
+ }
+ Choice::Clone => {
+ if query.is_empty() {
+ form.error = "Enter a GitHub URL or owner/repository".into();
+ form.child = Some(c);
+ return;
+ }
+ set_project(form, Project::Clone(query));
+ }
+ Choice::NewFolder => set_project(form, Project::New(query)),
+ }
+ form.child_active = false;
+ form.trail.clear();
+ form.focus = Field::Create;
+ form.error.clear();
+ refresh_form(app, form);
+ sync_git(app, form, false);
+}
+fn back(app: &mut App, form: &mut Form) -> bool {
+ if form.child_active {
+ if let Some(previous) = form.trail.pop() {
+ form.child = Some(previous);
+ if let Some(c) = &mut form.child {
+ if c.picker.busy.is_some() {
+ if let Choice::Folder(path) = &c.kind {
+ let path = path.clone();
+ c.generation = uuid::Uuid::new_v4().to_string();
+ load_folder(app, form, path);
+ }
+ }
+ }
+ } else {
+ form.child = None;
+ form.child_active = false;
+ }
+ form.error.clear();
+ true
+ } else if form.child.take().is_some() {
+ form.trail.clear();
+ true
+ } else {
+ false
+ }
+}
+pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
+ if key.code == KeyCode::Esc || (ctrl && matches!(key.code, KeyCode::Char('c' | 'g'))) {
+ if back(app, &mut form) {
+ app.modal = Some(Modal::NewHarness(form));
+ } else {
+ app.new_harness_draft = Some(form);
+ }
+ return;
+ }
+ if form.starting || key.kind == KeyEventKind::Repeat && key.code == KeyCode::Enter {
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ }
+ if form.attempt.is_some() {
+ let check = matches!(key.code, KeyCode::Enter | KeyCode::Char(' '));
+ app.modal = Some(Modal::NewHarness(form));
+ if check {
+ start(app);
+ }
+ return;
+ }
+ let mut launch = false;
+ if form.child_active {
+ if let Some(c) = &mut form.child {
+ let editing = c.kind.editing();
+ match key.code {
+ KeyCode::Enter => choose(app, &mut form),
+ KeyCode::Tab | KeyCode::BackTab => form.child_active = false,
+ KeyCode::Char('l') if ctrl && matches!(c.kind, Choice::Folder(_)) => {
+ let path = if let Choice::Folder(path) = &c.kind {
+ path.clone()
+ } else {
+ String::new()
+ };
+ let previous = form.child.take().unwrap();
+ step_into(app, &mut form, previous, Choice::Path, &path);
+ }
+ KeyCode::Up if !editing => c.picker.move_by(-1),
+ KeyCode::Down if !editing => c.picker.move_by(1),
+ KeyCode::PageUp if !editing => c.picker.move_by(-c.picker.page_rows.get().max(1)),
+ KeyCode::PageDown if !editing => c.picker.move_by(c.picker.page_rows.get().max(1)),
+ KeyCode::Char('p') if ctrl && !editing => c.picker.move_by(-1),
+ KeyCode::Char('n') if ctrl && !editing => c.picker.move_by(1),
+ KeyCode::Backspace => c.picker.backspace(false),
+ KeyCode::Delete => c.picker.delete_forward(),
+ KeyCode::Left => c.picker.qmove(-1, ctrl),
+ KeyCode::Right => c.picker.qmove(1, ctrl),
+ KeyCode::Char('b') if ctrl => c.picker.qmove(-1, false),
+ KeyCode::Char('f') if ctrl => c.picker.qmove(1, false),
+ KeyCode::Home | KeyCode::Char('a') if key.code == KeyCode::Home || ctrl => {
+ c.picker.qhome()
+ }
+ KeyCode::End | KeyCode::Char('e') if key.code == KeyCode::End || ctrl => {
+ c.picker.qend()
+ }
+ KeyCode::Char('u') if ctrl => c.picker.clear_query(),
+ KeyCode::Char('k') if ctrl => c.picker.kill_line(),
+ KeyCode::Char('w') if ctrl => c.picker.backspace(true),
+ KeyCode::Char('y') if ctrl => c.picker.yank(),
+ KeyCode::Char(ch)
+ if !key
+ .modifiers
+ .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
+ {
+ c.picker.type_char(ch)
+ }
+ _ => {}
+ }
+ }
+ if form
+ .child
+ .as_ref()
+ .is_some_and(|c| c.kind == Choice::Branch)
+ {
+ refresh_form(app, &mut form);
+ }
+ } else {
+ match key.code {
+ KeyCode::Up => {
+ form.move_by(-1);
+ reveal(app, &mut form);
+ }
+ KeyCode::Down => {
+ form.move_by(1);
+ reveal(app, &mut form);
+ }
+ KeyCode::Tab | KeyCode::BackTab => {
+ if form.child.is_some() {
+ form.child_active = true;
+ } else {
+ form.move_by(if key.code == KeyCode::BackTab { -1 } else { 1 });
+ reveal(app, &mut form);
+ }
+ }
+ KeyCode::Enter | KeyCode::Char(' ') => launch = activate(app, &mut form),
+ KeyCode::Right if form.child.is_some() || form.focus == Field::Worktree => {
+ activate(app, &mut form);
+ }
+ KeyCode::Left | KeyCode::PageUp | KeyCode::PageDown
+ if form.focus == Field::Worktree =>
+ {
+ activate(app, &mut form);
+ }
+ KeyCode::Char(ch)
+ if !key
+ .modifiers
+ .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
+ {
+ if form.child.is_some() {
+ form.child_active = true;
+ form.child.as_mut().unwrap().picker.type_char(ch);
+ } else {
+ let field = match ch {
+ 'a' => Some(Field::Agent),
+ 'p' => Some(Field::Project),
+ 'o' => Some(Field::Options),
+ _ => None,
+ };
+ if let Some(field) = field {
+ form.focus = field;
+ activate(app, &mut form);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ if form
+ .child
+ .as_ref()
+ .is_some_and(|c| c.kind == Choice::Branch)
+ {
+ refresh_form(app, &mut form);
+ }
+ app.modal = Some(Modal::NewHarness(form));
+ if launch {
+ start(app);
+ }
+}
+pub fn paste(form: &mut Form, text: &str) {
+ if form.starting || form.attempt.is_some() {
+ return;
+ }
+ if let Some(c) = &mut form.child {
+ form.child_active = true;
+ let mut line_break = false;
+ for ch in text.chars() {
+ if matches!(ch, '\r' | '\n') {
+ if !line_break {
+ c.picker.type_char(' ');
+ }
+ line_break = true;
+ } else {
+ line_break = false;
+ if !ch.is_control() {
+ c.picker.type_char(ch);
+ }
+ }
+ }
+ }
+}
+pub fn mouse(app: &mut App, mouse: MouseEvent) {
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
+ return;
+ };
+ let pos = Position::new(mouse.column, mouse.row);
+ let mut launch = false;
+ if !form.starting && form.attempt.is_some() {
+ if mouse.kind == MouseEventKind::Down(MouseButton::Left) {
+ launch = form
+ .hits
+ .iter()
+ .any(|(r, field)| *field == Field::Create && r.contains(pos));
+ if !form.area.contains(pos) {
+ app.new_harness_draft = Some(form);
+ return;
+ }
+ }
+ } else if !form.starting {
+ if matches!(
+ mouse.kind,
+ MouseEventKind::ScrollUp | MouseEventKind::ScrollDown
+ ) && form.child_area.contains(pos)
+ {
+ if let Some(c) = &mut form.child {
+ form.child_active = true;
+ c.picker.move_by(if mouse.kind == MouseEventKind::ScrollUp {
+ -1
+ } else {
+ 1
+ });
+ }
+ } else if mouse.kind == MouseEventKind::Down(MouseButton::Left) {
+ if form.child.is_some() && form.child_area.contains(pos) {
+ form.child_active = true;
+ let c = form.child.as_mut().unwrap();
+ if let Some((_, index)) = c.picker.row_at.iter().find(|(y, _)| *y == mouse.row) {
+ c.picker.cursor = *index;
+ choose(app, &mut form);
+ }
+ } else if let Some((_, field)) = form.hits.iter().find(|(r, _)| r.contains(pos)) {
+ form.focus = *field;
+ reveal(app, &mut form);
+ launch = activate(app, &mut form);
+ } else if !form.area.contains(pos) {
+ if !back(app, &mut form) {
+ app.new_harness_draft = Some(form);
+ return;
+ }
+ }
+ }
+ }
+ app.modal = Some(Modal::NewHarness(form));
+ if launch {
+ start(app);
+ }
+}
+
+/// Validate launch choices using the selected machine; no side effects occur while browsing.
+pub fn start(app: &mut App) {
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
+ return;
+ };
+ if form.starting {
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ }
+ if let Some(attempt) = form.attempt.clone() {
+ form.starting = true;
+ form.checking = true;
+ form.error.clear();
+ let id = form.id.clone();
+ app.modal = Some(Modal::NewHarness(form));
+ crate::input::check_creation(app, id, attempt);
+ return;
+ }
+ let fail = if form.git_loading {
+ Some("Checking the project…".into())
+ } else if form.git["error"].is_string() {
+ Some("Could not read this project. Open Options → Branch to retry.".into())
+ } else {
+ form.project_payload().err()
+ };
+ if let Some(error) = fail {
+ form.error = error;
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ }
+ let Some(link) = app.link(&form.draft.machine) else {
+ form.error = "That machine is not connected".into();
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ };
+ let id = form.id.clone();
+ let model = form.draft.model.is_some();
+ let profile = form.draft.what.engine == "codex"
+ && form.draft.model.is_none()
+ && form.draft.profile.is_some();
+ let package = form.draft.what.dsh.is_some();
+ if !model && !profile && !package {
+ launch(app, form, true);
+ return;
+ }
+ form.starting = true;
+ form.error.clear();
+ app.modal = Some(Modal::NewHarness(form));
+ app.spawn(async move{
+ let models=async{if model{link.rpc("grid_models_list",json!({"rowState":true}),Duration::from_secs(30)).await.ok()}else{None}};
+ let profiles=async{if profile{link.rpc("codex_profiles_list",json!({}),Duration::from_secs(20)).await.ok()}else{None}};
+ let packages=async{if package{link.rpc("dsh_list",json!({}),Duration::from_secs(20)).await.ok()}else{None}};
+ tokio::join!(models,profiles,packages)
+ },move|app,(models,profiles,packages)|{
+ let visible=matches!(&app.modal,Some(Modal::NewHarness(f))if f.id==id);
+ let mut result=None;with_form(app,&id,|_,form|{form.starting=false;
+ if let Some((grid,id,_))=&form.draft.model{let expected=json!([grid,id]).to_string();if !data::model_rows(&models.unwrap_or(Value::Null),&form.draft.what.engine).iter().any(|r|r.id==expected&&!r.disabled){form.error="Model unavailable here. Choose a model or your subscription.".into();return}}
+ if profile{let (machine,path,_)=form.draft.profile.as_ref().unwrap();if machine!=&form.draft.machine{form.error="Choose a profile on this machine.".into();return}if !profiles.unwrap_or(Value::Null)["profiles"].as_array().into_iter().flatten().any(|p|p["path"].as_str()==Some(path)){form.error="Profile unavailable here. Choose another profile.".into();return}}
+ if let Some(dsh)=&form.draft.what.dsh{let catalog=packages.unwrap_or(Value::Null);let row=catalog["dsh"].as_array().into_iter().flatten().find(|r|r["id"].as_str()==Some(dsh));
+ let Some(row)=row else{form.error="This harness is unavailable on this machine. Choose an agent or harness.".into();return};
+ if row["installed"]==false{form.error="Install this harness from the Store first, then retry.".into();return}
+ let compatible=row["engines"].as_array().filter(|a|!a.is_empty()).map(|a|a.iter().any(|e|e.as_str()==Some(&form.draft.what.engine))).unwrap_or_else(||row["engine"].as_str().unwrap_or("claude")==form.draft.what.engine);
+ if !compatible{form.error="Choose a compatible coding agent for this harness.".into();return}
+ }result=Some(());
+ });
+ if result.is_some(){let form=if visible{let Some(Modal::NewHarness(f))=app.modal.take()else{return};f}else{let Some(f)=app.new_harness_draft.take()else{return};f};launch(app,form,visible);}
+ });
+}
+fn launch(app: &mut App, mut form: Box<Form>, visible: bool) {
+ let d = form.draft.clone();
+ let (cwd, mut extra) = match form.project_payload() {
+ Ok(v) => v,
+ Err(e) => {
+ form.error = e;
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ }
+ };
+ if d.what.engine == "terminal" && cwd.is_none() {
+ form.error = "Choose an existing folder for a terminal".into();
+ app.modal = Some(Modal::NewHarness(form));
+ return;
+ }
+ extra["permissionMode"] = Value::Null;
+ extra["bypassPermission"] = json!(false);
+ if !data::modes(&d.what.engine).is_empty() {
+ extra["permissionMode"] = json!(d.permission);
+ extra["bypassPermission"] = json!(matches!(d.permission.as_str(), "auto" | "full"));
+ }
+ if let Some((grid, id, _)) = &d.model {
+ extra["gridName"] = json!(grid);
+ extra["gridModel"] = json!(id);
+ }
+ if d.what.engine == "codex" && d.model.is_none() {
+ if let Some((_, path, _)) = &d.profile {
+ extra["codexHome"] = json!(path);
+ }
+ }
+ let id = form.id.clone();
+ let previous = app.modal.take();
+ app.modal = Some(Modal::NewHarness(form));
+ crate::input::create_opts(
+ app,
+ d.machine,
+ d.what,
+ cwd,
+ None,
+ false,
+ crate::input::NewOpts {
+ extra: Some(extra),
+ form_id: Some(id),
+ ..Default::default()
+ },
+ );
+ if !visible {
+ if let Some(Modal::NewHarness(form)) = app.modal.take() {
+ app.new_harness_draft = Some(form);
+ }
+ app.modal = previous;
+ }
+}
+/// Apply the daemon's receipt before deciding whether another launch is allowed.
+/// A status check is read-only, even after a reconnect or a daemon upgrade.
+pub fn creation_reply(
+ app: &mut App,
+ id: &str,
+ reply: &Result<Value, crate::daemon::RpcError>,
+ checking: bool,
+) -> bool {
+ let mut created = false;
+ with_form(app, id, |app, form| {
+ let Some(attempt) = &form.attempt else { return };
+ let outcome = receipt::outcome(&attempt.id, reply, checking);
+ form.starting = false;
+ form.checking = false;
+ match outcome {
+ receipt::Outcome::Created => created = true,
+ receipt::Outcome::Failed {
+ message,
+ prepared_folder,
+ } => {
+ form.attempt = None;
+ form.error = message;
+ if let Some(path) = prepared_folder {
+ set_project(form, Project::Folder(path.clone()));
+ form.prepared_folder = Some(path);
+ form.draft.worktree = Some(false);
+ sync_git(app, form, true);
+ }
+ }
+ receipt::Outcome::Uncertain(message) => form.error = message,
+ }
+ });
+ created
+}
+
+pub fn created(app: &mut App, id: &str, agent: &Value) {
+ with_form(app, id, |_, form| {
+ if !matches!(form.draft.project, Project::Folder(_)) {
+ if let Some(cwd) = agent
+ .pointer("/project/cwd")
+ .or_else(|| agent.get("cwd"))
+ .and_then(Value::as_str)
+ {
+ form.draft.project = Project::Folder(cwd.into());
+ }
+ }
+ });
+ completed(app, id, None);
+}
+pub fn completed(app: &mut App, id: &str, error: Option<String>) {
+ let mut success = false;
+ with_form(app, id, |_, form| {
+ form.starting = false;
+ if let Some(error) = error {
+ form.error = error;
+ } else {
+ remember(form);
+ success = true;
+ }
+ });
+ if success {
+ if matches!(&app.modal,Some(Modal::NewHarness(f))if f.id==id) {
+ app.modal = None;
+ }
+ if app.new_harness_draft.as_ref().is_some_and(|f| f.id == id) {
+ app.new_harness_draft = None;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app() -> App {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (150, 42));
+ app.fleet.local_id = "local".into();
+ app.fleet.machines.push(crate::fleet::Machine {
+ id: "local".into(),
+ name: "studio".into(),
+ local: true,
+ status: "online".into(),
+ reach: crate::fleet::Reach::Ready,
+ });
+ app.homes.insert("local".into(), "/home/dev".into());
+ app
+ }
+
+ #[tokio::test]
+ async fn draft_survives_picker_escape_and_late_refresh() {
+ let mut app = app();
+ open(&mut app, None, Some("/home/dev/project".into()));
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
+ panic!()
+ };
+ child(&mut app, &mut form, Choice::Agent, "codex");
+ app.modal = Some(Modal::NewHarness(form));
+ refresh(&mut app);
+ let Some(Modal::NewHarness(form)) = app.modal.take() else {
+ panic!()
+ };
+ assert_eq!(form.child.as_ref().unwrap().picker.query, "codex");
+ key(
+ &mut app,
+ form,
+ KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
+ );
+ let Some(Modal::NewHarness(form)) = &app.modal else {
+ panic!()
+ };
+ assert!(form.child.is_none());
+ assert!(matches!(&form.draft.project, Project::Folder(p) if p == "/home/dev/project"));
+ app.modal = Some(Modal::Confirm {
+ prompt: "keep me".into(),
+ command: "".into(),
+ key: 'y',
+ enter_yes: false,
+ });
+ refresh(&mut app);
+ assert!(matches!(app.modal, Some(Modal::Confirm { .. })));
+ }
+
+ #[tokio::test]
+ async fn form_and_picker_fit_every_terminal_size() {
+ let mut app = app();
+ open(&mut app, None, None);
+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
+ panic!()
+ };
+ for expanded in [false, true] {
+ form.expanded = expanded;
+ for chooser in [false, true] {
+ if chooser {
+ child(&mut app, &mut form, Choice::Agent, "");
+ } else {
+ form.child = None;
+ }
+ for width in [1, 10, 21, 22, 45, 80, 109, 110, 150] {
+ for height in [1, 4, 5, 10, 14, 24, 42] {
+ let area = Rect::new(0, 0, width, height);
+ let mut buf = Buffer::empty(area);
+ if let Some(cursor) = draw(&mut buf, area, &mut form) {
+ assert!(area.contains(cursor), "{area:?} {cursor:?}");
+ }
+ for (hit, _) in &form.hits {
+ assert_eq!(hit.intersection(area), *hit);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn terminal_and_agent_options_match_the_launch_contract() {
+ let mut app = app();
+ open(&mut app, None, Some("/home/dev/repo".into()));
+ let Some(Modal::NewHarness(mut f)) = app.modal.take() else {
+ panic!()
+ };
+ f.expanded = true;
+ f.draft.permission = "readOnly".into();
+ set_engine(&mut f, "claude");
+ assert_eq!(f.draft.permission, "auto");
+ f.draft.permission = "plan".into();
+ set_engine(&mut f, "codex");
+ assert_eq!(f.draft.permission, "readOnly");
+ set_engine(&mut f, "terminal");
+ assert!(!f.fields().contains(&Field::Approvals));
+ assert!(!f.fields().contains(&Field::Model));
+ assert!(!f.fields().contains(&Field::Profile));
+ child(&mut app, &mut f, Choice::Clone, "");
+ paste(&mut f, "owner/\r\nrepository");
+ assert_eq!(f.child.as_ref().unwrap().picker.query, "owner/ repository");
+ }
+
+ #[tokio::test]
+ async fn delayed_callbacks_only_update_their_own_dismissed_draft() {
+ let mut app = app();
+ open(&mut app, None, Some("/home/dev/repo".into()));
+ let Some(Modal::NewHarness(f)) = app.modal.take() else {
+ panic!()
+ };
+ let id = f.id.clone();
+ key(&mut app, f, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ assert!(app.modal.is_none());
+ app.modal = Some(Modal::Confirm {
+ prompt: "stay here".into(),
+ command: "".into(),
+ key: 'y',
+ enter_yes: false,
+ });
+ with_form(&mut app, &id, |_, f| f.error = "late error".into());
+ assert!(matches!(app.modal, Some(Modal::Confirm { .. })));
+ assert_eq!(app.new_harness_draft.as_ref().unwrap().error, "late error");
+ with_form(&mut app, "stale-id", |_, _| panic!("wrong draft"));
+ }
+
+ #[tokio::test]
+ async fn uncertain_launch_keeps_its_machine_and_choices_until_confirmed() {
+ let mut app = app();
+ open(&mut app, None, None);
+ let Some(Modal::NewHarness(mut f)) = app.modal.take() else {
+ panic!()
+ };
+ let id = f.id.clone();
+ f.attempt = Some(Creation {
+ id: "intent".into(),
+ machine: "local".into(),
+ session: 0,
+ });
+ app.modal = Some(Modal::NewHarness(f));
+ assert!(!creation_reply(
+ &mut app,
+ &id,
+ &Err(crate::daemon::RpcError::new("TIMEOUT", "")),
+ false
+ ));
+ let Some(Modal::NewHarness(f)) = app.modal.take() else {
+ panic!()
+ };
+ key(
+ &mut app,
+ f,
+ KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE),
+ );
+ let Some(Modal::NewHarness(f)) = app.modal.take() else {
+ panic!()
+ };
+ assert!(
+ f.child.is_none(),
+ "choices cannot change an unresolved launch"
+ );
+ key(&mut app, f, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ // Even an explicit new destination must recover the existing attempt first.
+ open(&mut app, Some("local".into()), Some("/another".into()));
+ let Some(Modal::NewHarness(f)) = &app.modal else {
+ panic!()
+ };
+ assert_eq!(f.id, id);
+ assert_eq!(f.describe(Field::Create).0, "Check status");
+ assert!(!creation_reply(
+ &mut app,
+ &id,
+ &Ok(json!({"creationId":"wrong", "state":"created", "agent":{"id":"wrong"}})),
+ true
+ ));
+ assert!(creation_reply(
+ &mut app,
+ &id,
+ &Ok(json!({"creationId":"intent", "state":"created", "agent":{"id":"original"}})),
+ true
+ ));
+ }
+
+ #[tokio::test]
+ async fn confirmed_failure_reuses_prepared_worktree_without_preparing_another() {
+ let mut app = app();
+ open(&mut app, None, None);
+ let Some(Modal::NewHarness(mut f)) = app.modal.take() else {
+ panic!()
+ };
+ let id = f.id.clone();
+ f.attempt = Some(Creation {
+ id: "intent".into(),
+ machine: "local".into(),
+ session: 0,
+ });
+ app.modal = Some(Modal::NewHarness(f));
+ assert!(!creation_reply(
+ &mut app,
+ &id,
+ &Ok(
+ json!({"creationId":"intent", "state":"failed", "failure":{"code":"ENGINE_UNAVAILABLE"}, "preparedFolder":"/repo/worktree"})
+ ),
+ true
+ ));
+ let Some(Modal::NewHarness(f)) = &mut app.modal else {
+ panic!()
+ };
+ assert!(
+ f.attempt.is_none(),
+ "a new deliberate retry gets a fresh receipt"
+ );
+ f.git = json!({"isGit":true, "branch":"feature", "defaultRef":"refs/heads/main"});
+ assert_eq!(
+ f.project_payload().unwrap(),
+ (Some("/repo/worktree".into()), json!({}))
+ );
+ set_project(f, Project::Folder("/another".into()));
+ assert!(f.prepared_folder.is_none());
+ }
+
+ #[test]
+ fn home_abbreviation_requires_a_path_boundary() {
+ assert_eq!(short_path("/home/dev/project", "/home/dev"), "~/project");
+ assert_eq!(
+ short_path("/home/developer/project", "/home/dev"),
+ "/home/developer/project"
+ );
+ }
+}
diff --git a/tui/src/new_harness/data.rs b/tui/src/new_harness/data.rs
new file mode 100644
index 000000000..4cfa87038
--- /dev/null
+++ b/tui/src/new_harness/data.rs
@@ -0,0 +1,306 @@
+//! The desktop New Harness launch choices, using the same daemon contracts.
+use super::{Draft, Project};
+use crate::{picker::Row, theme};
+use serde_json::{Value, json};
+
+pub fn modes(engine: &str) -> &'static [(&'static str, &'static str)] {
+ match engine {
+ "claude" => &[
+ ("auto", "Auto-approve"),
+ ("acceptEdits", "Accept edits"),
+ ("plan", "Plan first"),
+ ("ask", "Ask first"),
+ ("full", "Skip all checks"),
+ ],
+ "codex" => &[
+ ("readOnly", "Read only"),
+ ("ask", "Ask first"),
+ ("auto", "Auto-approve"),
+ ("full", "Full access"),
+ ],
+ "cursor" | "opencode" => &[("auto", "Auto-approve"), ("ask", "Ask first")],
+ _ => &[],
+ }
+}
+pub fn mode_label(engine: &str, mode: &str) -> String {
+ modes(engine)
+ .iter()
+ .find(|(id, _)| *id == mode)
+ .map(|(_, label)| *label)
+ .unwrap_or(mode)
+ .into()
+}
+pub fn subscription(engine: &str) -> &str {
+ match engine {
+ "codex" => "OpenAI",
+ "claude" => "Anthropic",
+ _ => theme::engine_label(engine),
+ }
+}
+pub fn branches(info: &Value) -> &[Value] {
+ info["branches"]
+ .as_array()
+ .map(Vec::as_slice)
+ .unwrap_or(&[])
+}
+pub fn git(info: &Value) -> bool {
+ info["isGit"].as_bool() == Some(true)
+}
+pub fn branch_ref(draft: &Draft, info: &Value) -> Option<String> {
+ if let Some(r) = &draft.branch {
+ return Some(r.clone());
+ }
+ let refs: Vec<_> = branches(info)
+ .iter()
+ .filter_map(|b| b["ref"].as_str())
+ .collect();
+ if draft.worktree.unwrap_or(git(info)) {
+ ["refs/heads/main", "refs/remotes/origin/main"]
+ .into_iter()
+ .find(|r| refs.contains(r))
+ .map(str::to_string)
+ } else {
+ info["branch"]
+ .as_str()
+ .map(|b| format!("refs/heads/{b}"))
+ .filter(|r| refs.contains(&r.as_str()))
+ }
+}
+pub fn branch_name(reference: &str) -> &str {
+ reference
+ .strip_prefix("refs/heads/")
+ .or_else(|| reference.strip_prefix("refs/remotes/"))
+ .unwrap_or(reference)
+}
+pub fn valid_branch(name: &str) -> bool {
+ !name.is_empty()
+ && !name.starts_with(['-', '/', '.'])
+ && !name.ends_with(['/', '.'])
+ && !name.ends_with(".lock")
+ && !name.contains([' ', '\t', '\n', '\\', '~', '^', ':', '?', '*', '['])
+ && !name.contains("..")
+ && !name.contains("@{")
+ && !name.contains("//")
+ && name
+ .split('/')
+ .all(|part| !part.starts_with('.') && !part.ends_with(".lock"))
+ && name != "@"
+}
+pub fn branch_rows(info: &Value, worktree: bool, query: &str) -> Vec<Row> {
+ let locals: Vec<_> = branches(info)
+ .iter()
+ .filter(|b| b["remote"] != true)
+ .filter_map(|b| b["name"].as_str())
+ .collect();
+ let mut rows = Vec::new();
+ for branch in branches(info) {
+ let (Some(reference), Some(name)) = (branch["ref"].as_str(), branch["name"].as_str())
+ else {
+ continue;
+ };
+ if branch["remote"] == true
+ && (!worktree
+ || name
+ .split_once('/')
+ .is_some_and(|(_, short)| locals.contains(&short)))
+ {
+ continue;
+ }
+ let mut row = Row::new(reference, name).extra(reference);
+ if branch["worktree"].is_string() && info["branch"].as_str() != Some(name) {
+ row.label.push_str(" · in its worktree");
+ }
+ rows.push(row);
+ }
+ let query = query.trim();
+ if valid_branch(query) && !locals.contains(&query) {
+ rows.push(Row::new(
+ format!("new:{query}"),
+ format!("Create branch {query}"),
+ ));
+ }
+ rows
+}
+
+/// Prepare only a request. The daemon owns branch/worktree creation, and does it only at Start.
+pub fn project_payload(d: &Draft, info: &Value) -> Result<(Option<String>, Value), String> {
+ let mut extra = json!({});
+ let folder = match &d.project {
+ Project::New(name) => {
+ extra["projectSource"] = json!("new");
+ if !name.is_empty() {
+ extra["projectName"] = json!(name);
+ }
+ return Ok((None, extra));
+ }
+ Project::Clone(url) => {
+ extra["projectSource"] = json!("remote");
+ extra["repositoryUrl"] = json!(url);
+ return Ok((None, extra));
+ }
+ Project::Folder(folder) if folder.starts_with('/') => folder,
+ _ => return Err("Choose a project folder first".into()),
+ };
+ if d.what.engine == "terminal" || !git(info) {
+ return Ok((Some(folder.clone()), extra));
+ }
+ let worktree = d.worktree.unwrap_or(true);
+ let reference = branch_ref(d, info);
+ if worktree && reference.is_none() {
+ return Err("Choose a branch under Options, or turn Worktree off".into());
+ }
+ let Some(reference) = reference else {
+ return Ok((Some(folder.clone()), extra));
+ };
+ extra["projectSource"] = json!(if worktree { "worktree" } else { "branch" });
+ extra["gitSource"] = json!(folder);
+ extra["branchRef"] = json!(reference);
+ if let Some(name) = &d.new_branch {
+ if !valid_branch(name) {
+ return Err("Choose a valid branch name".into());
+ }
+ extra["branchName"] = json!(name);
+ if !worktree {
+ extra["branchRef"] = json!(format!("refs/heads/{name}"));
+ }
+ } else if worktree {
+ let name = branch_name(&reference);
+ let is_default = name == "main"
+ || name == "origin/main"
+ || info["defaultRef"].as_str() == Some(&reference)
+ || info["defaultRef"]
+ .as_str()
+ .and_then(|r| r.strip_prefix("refs/remotes/"))
+ .and_then(|r| r.split_once('/'))
+ .is_some_and(|(_, short)| short == name);
+ let local_name = reference
+ .strip_prefix("refs/heads/")
+ .or_else(|| name.split_once('/').map(|(_, n)| n));
+ let local = branches(info)
+ .iter()
+ .find(|b| b["remote"] != true && b["name"].as_str() == local_name);
+ if !is_default {
+ if let Some(local) = local {
+ if local["name"] != info["branch"] {
+ extra["branchRef"] = local["ref"].clone();
+ if local["worktree"].is_string() {
+ extra["projectSource"] = json!("branch");
+ } else {
+ extra["branchName"] = local["name"].clone();
+ extra["branchMode"] = json!("existing");
+ }
+ }
+ } else if let Some(name) = local_name {
+ extra["branchName"] = json!(name);
+ }
+ }
+ }
+ Ok((None, extra))
+}
+
+pub fn supports_models(catalog: &Value, engine: &str) -> bool {
+ catalog["supportsModelLaunch"] == true
+ && catalog["localModelEngines"]
+ .as_array()
+ .map(|a| a.iter().any(|e| e.as_str() == Some(engine)))
+ .unwrap_or(true)
+}
+pub fn model_rows(catalog: &Value, engine: &str) -> Vec<Row> {
+ let mut rows = vec![Row::new("subscription", subscription(engine)).group("Subscription")];
+ if supports_models(catalog, engine) {
+ for grid in catalog["grids"].as_array().into_iter().flatten() {
+ let Some(grid_name) = grid["name"].as_str() else {
+ continue;
+ };
+ for model in grid["models"].as_array().into_iter().flatten() {
+ let Some(id) = model["id"].as_str() else {
+ continue;
+ };
+ let node = model["node"].as_str().unwrap_or("");
+ let label = format!("{id}{}{}", if node.is_empty() { "" } else { " · " }, node);
+ let mut row = Row::new(json!([grid_name, id]).to_string(), label)
+ .extra(grid_name)
+ .group(if grid["own"] == true {
+ "On your machines".into()
+ } else {
+ format!("Shared · {grid_name}")
+ });
+ row.disabled = model["unavailable"].is_object()
+ || model["unavailable"].as_bool() == Some(true);
+ if row.disabled {
+ row.label.push_str(" · offline");
+ }
+ rows.push(row);
+ }
+ }
+ }
+ rows.push(Row::new("refresh", "Refresh models"));
+ rows
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn draft() -> Draft {
+ Draft {
+ machine: "local".into(),
+ what: crate::modal::What {
+ engine: "codex".into(),
+ dsh: None,
+ label: "Codex".into(),
+ },
+ project: Project::Folder("/home/dev/repo".into()),
+ permission: "auto".into(),
+ worktree: None,
+ branch: None,
+ new_branch: None,
+ model: None,
+ profile: None,
+ }
+ }
+ fn info() -> Value {
+ json!({"isGit":true,"branch":"main","branches":[{"name":"main","ref":"refs/heads/main","remote":false},{"name":"feature","ref":"refs/heads/feature","remote":false},{"name":"open","ref":"refs/heads/open","remote":false,"worktree":"/home/dev/open"}]})
+ }
+ #[test]
+ fn launch_matches_the_desktop_git_choices() {
+ let mut d = draft();
+ let i = info();
+ assert_eq!(
+ project_payload(&d, &i).unwrap().1,
+ json!({"projectSource":"worktree","gitSource":"/home/dev/repo","branchRef":"refs/heads/main"})
+ );
+ d.branch = Some("refs/heads/feature".into());
+ assert_eq!(project_payload(&d, &i).unwrap().1["branchMode"], "existing");
+ d.branch = Some("refs/heads/open".into());
+ assert_eq!(
+ project_payload(&d, &i).unwrap().1["projectSource"],
+ "branch"
+ );
+ d.worktree = Some(false);
+ d.new_branch = Some("new-feature".into());
+ assert_eq!(
+ project_payload(&d, &i).unwrap().1["branchRef"],
+ "refs/heads/new-feature"
+ );
+ d = draft();
+ assert!(project_payload(&d, &json!({"isGit":true,"branches":[]})).is_err());
+ d.worktree = Some(false);
+ assert!(project_payload(&d, &json!({"isGit":true,"branches":[]})).is_ok());
+ d.what.engine = "terminal".into();
+ assert_eq!(
+ project_payload(&d, &i).unwrap().0.as_deref(),
+ Some("/home/dev/repo")
+ );
+ assert!(!modes("codex").iter().any(|(m, _)| *m == "plan"));
+ assert!(modes("claude").iter().any(|(m, _)| *m == "plan"));
+ assert!(modes("terminal").is_empty());
+ }
+ #[test]
+ fn models_retain_grid_identity_and_do_not_offer_offline_routes() {
+ let catalog = json!({"supportsModelLaunch":true,"localModelEngines":["codex"],"grids":[{"name":"one","models":[{"id":"same","node":"local"}]},{"name":"two","models":[{"id":"same","node":"remote","unavailable":{"machine":"remote"}}]}]});
+ let rows = model_rows(&catalog, "codex");
+ assert_ne!(rows[1].id, rows[2].id);
+ assert!(rows[2].disabled);
+ assert_eq!(model_rows(&catalog, "cursor").len(), 2);
+ }
+}
diff --git a/tui/src/new_harness/receipt.rs b/tui/src/new_harness/receipt.rs
new file mode 100644
index 000000000..52507237c
--- /dev/null
+++ b/tui/src/new_harness/receipt.rs
@@ -0,0 +1,236 @@
+//! Creation receipts distinguish a refused launch from a lost answer. Follow the
+//! same contract as desktop's AgentCreationAttempt and daemon AgentCreationReceipts.
+use crate::daemon::RpcError;
+use serde_json::Value;
+
+#[derive(Clone)]
+pub(crate) struct Creation {
+ pub id: String,
+ pub machine: String,
+ pub session: u32,
+}
+
+#[derive(Debug, PartialEq)]
+pub enum Outcome {
+ Created,
+ Failed {
+ message: String,
+ prepared_folder: Option<String>,
+ },
+ Uncertain(String),
+}
+
+fn uncertain() -> Outcome {
+ Outcome::Uncertain("Launch not confirmed. Check status before starting another.".into())
+}
+fn failed(code: &str, detail: Option<&str>, prepared_folder: Option<String>) -> Outcome {
+ Outcome::Failed {
+ message: format!(
+ "Could not start it: {}",
+ detail.filter(|s| !s.is_empty()).unwrap_or(code)
+ ),
+ prepared_folder,
+ }
+}
+
+pub fn outcome(id: &str, reply: &Result<Value, RpcError>, checking: bool) -> Outcome {
+ let value = match reply {
+ Ok(value) => value,
+ Err(error) => {
+ // Only explicit refusals before launch can unlock the form. An error
+ // from a status check says nothing about the original launch.
+ if !checking
+ && matches!(
+ error.code.as_str(),
+ "INVALID_PROJECT_SOURCE"
+ | "INVALID_REPOSITORY"
+ | "PROJECT_EXISTS"
+ | "CWD_NOT_FOUND"
+ | "INVALID_CWD"
+ | "INVALID_ENGINE"
+ | "INVALID_GRID"
+ | "GRID_UNAVAILABLE"
+ | "INVALID_CODEX_HOME"
+ | "INVALID_DSH"
+ | "PROMPT_UNSUPPORTED"
+ | "PROMPT_TOO_LONG"
+ | "INVALID_PROMPT"
+ | "AGENT_UNSUPPORTED"
+ | "INVALID_AGENT"
+ | "INVALID_PERMISSION_MODE"
+ | "TMUX_UNAVAILABLE"
+ | "CODEX_CLI_TOO_OLD"
+ | "TMUX_TOO_OLD_FOR_GRID"
+ | "GRID_CONFIG_FAILED"
+ | "UNSUPPORTED_ON_REMOTE"
+ | "UNSUPPORTED"
+ | "SESSION_OPEN_ELSEWHERE"
+ | "SESSION_IN_HARNESS"
+ | "SESSION_NOT_FOUND"
+ | "SESSION_FOLDER_GONE"
+ | "SESSION_OPEN_IN_TERMINAL"
+ | "SESSION_BUSY_IN_TERMINAL"
+ | "SESSION_STOP_FAILED"
+ | "INVALID_SESSION"
+ )
+ {
+ return failed(&error.code, Some(&error.detail), None);
+ }
+ return uncertain();
+ }
+ };
+ if (checking || value.get("creationId").is_some() || value.get("state").is_some())
+ && value["creationId"].as_str() != Some(id)
+ {
+ return uncertain();
+ }
+ match value["state"].as_str() {
+ Some("failed") => {
+ let Some(code) = value
+ .pointer("/failure/code")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ else {
+ return uncertain();
+ };
+ let prepared_folder = match value.get("preparedFolder") {
+ None => None,
+ Some(Value::String(path))
+ if path.starts_with('/') && !path.chars().any(char::is_control) =>
+ {
+ Some(path.clone())
+ }
+ _ => return uncertain(),
+ };
+ failed(
+ code,
+ value.pointer("/failure/detail").and_then(Value::as_str),
+ prepared_folder,
+ )
+ }
+ Some("pending") => {
+ Outcome::Uncertain("Still starting your harness. Check again in a moment.".into())
+ }
+ Some("missing") => {
+ Outcome::Uncertain("No record of this launch. Use Open Harness to look for it.".into())
+ }
+ Some("unconfirmed") => {
+ Outcome::Uncertain("Launch outcome unknown. Use Open Harness to look for it.".into())
+ }
+ Some("unavailable") => Outcome::Failed {
+ message: "This harness started but is no longer available. You can start a new one."
+ .into(),
+ prepared_folder: None,
+ },
+ Some("created") | None
+ if value
+ .pointer("/agent/id")
+ .and_then(Value::as_str)
+ .is_some_and(|s| !s.is_empty()) =>
+ {
+ Outcome::Created
+ }
+ _ => uncertain(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn confirmed_refusal_unlocks_retry_and_keeps_the_prepared_folder() {
+ let reply = Ok(
+ json!({"creationId":"intent", "state":"failed", "failure":{"code":"ENGINE_UNAVAILABLE", "detail":"Sign in first"}, "preparedFolder":"/projects/prepared"}),
+ );
+ assert_eq!(
+ outcome("intent", &reply, false),
+ Outcome::Failed {
+ message: "Could not start it: Sign in first".into(),
+ prepared_folder: Some("/projects/prepared".into())
+ }
+ );
+ // The same persisted failure discovered after reconnect is also definitive.
+ assert_eq!(
+ outcome("intent", &reply, true),
+ outcome("intent", &reply, false)
+ );
+ assert!(matches!(
+ outcome(
+ "intent",
+ &Err(RpcError::new("INVALID_DSH", "Install first")),
+ false
+ ),
+ Outcome::Failed { .. }
+ ));
+ }
+
+ #[test]
+ fn ambiguous_results_never_allow_a_fresh_launch() {
+ for state in ["missing", "pending", "unconfirmed", "unexpected"] {
+ assert!(matches!(
+ outcome(
+ "intent",
+ &Ok(json!({"creationId":"intent", "state":state})),
+ true
+ ),
+ Outcome::Uncertain(_)
+ ));
+ }
+ for code in [
+ "TIMEOUT",
+ "DISCONNECTED",
+ "INTERNAL",
+ "SPAWN_FAILED",
+ "REGISTRATION_FAILED",
+ "CREATION_STORAGE_FAILED",
+ ] {
+ assert!(matches!(
+ outcome("intent", &Err(RpcError::new(code, "")), false),
+ Outcome::Uncertain(_)
+ ));
+ }
+ assert!(matches!(
+ outcome("intent", &Err(RpcError::new("INVALID_DSH", "")), true),
+ Outcome::Uncertain(_)
+ ));
+ }
+
+ #[test]
+ fn recovery_requires_the_original_receipt_and_an_agent() {
+ let created = json!({"creationId":"intent", "state":"created", "agent":{"id":"one"}});
+ assert_eq!(
+ outcome("intent", &Ok(created.clone()), true),
+ Outcome::Created
+ );
+ assert!(matches!(
+ outcome("another", &Ok(created), true),
+ Outcome::Uncertain(_)
+ ));
+ assert!(matches!(
+ outcome(
+ "intent",
+ &Ok(json!({"creationId":"intent", "state":"created"})),
+ false
+ ),
+ Outcome::Uncertain(_)
+ ));
+ assert!(matches!(
+ outcome(
+ "intent",
+ &Ok(json!({"creationId":"intent", "state":"failed"})),
+ false
+ ),
+ Outcome::Uncertain(_)
+ ));
+ // Older daemons can answer an initial create without receipts, but a status
+ // answer must always identify the request it describes.
+ let legacy = Ok(json!({"agent":{"id":"one"}}));
+ assert_eq!(outcome("intent", &legacy, false), Outcome::Created);
+ assert!(matches!(
+ outcome("intent", &legacy, true),
+ Outcome::Uncertain(_)
+ ));
+ }
+}
diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rs
new file mode 100644
index 000000000..d97a8a620
--- /dev/null
+++ b/tui/src/new_harness/view.rs
@@ -0,0 +1,318 @@
+//! Terminal rendering of the compact desktop form.
+use super::*;
+
+fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) {
+ if width == 0 {
+ return;
+ }
+ let mut out = String::new();
+ let mut used = 0;
+ let limit = width as usize;
+ let trunc = text.width() > limit;
+ for ch in text.chars().filter(|c| !c.is_control()) {
+ let w = ch.width().unwrap_or(0);
+ if used + w > limit.saturating_sub(usize::from(trunc)) {
+ break;
+ }
+ out.push(ch);
+ used += w;
+ }
+ if trunc {
+ out.push('…');
+ }
+ buf.set_stringn(x, y, out, width as usize, style);
+}
+
+fn panel(buf: &mut Buffer, r: Rect, title: &str, base: Style, border: Style) {
+ crate::term_out::clear_extras(r);
+ for y in r.y..r.bottom() {
+ for x in r.x..r.right() {
+ if let Some(c) = buf.cell_mut((x, y)) {
+ c.reset();
+ c.set_style(base);
+ }
+ }
+ }
+ Block::default()
+ .borders(Borders::ALL)
+ .border_type(BorderType::Rounded)
+ .border_style(border)
+ .render(r, buf);
+ let _ = title;
+}
+
+pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {
+ form.hits.clear();
+ form.area = Rect::default();
+ form.child_area = Rect::default();
+ if body.width < 22 || body.height < 5 {
+ put(
+ buf,
+ body.x,
+ body.y,
+ body.width,
+ "New Harness · resize or Esc",
+ Style::default(),
+ );
+ return None;
+ }
+ let (_, foreground, light) = theme::palette();
+ let base = if theme::no_color() {
+ Style::default()
+ } else {
+ theme::fg(foreground).bg(theme::depth_fit(if light {
+ Color::Rgb(247, 247, 247)
+ } else {
+ Color::Rgb(25, 25, 25)
+ }))
+ };
+ let accent = base.patch(theme::bold(theme::accent()));
+ let muted = base.patch(theme::fg(if light {
+ Color::Rgb(92, 98, 104)
+ } else {
+ Color::Rgb(167, 173, 180)
+ }));
+ let border = base.patch(theme::fg(theme::pane_palette().active_foreground));
+ // Keep the working panes visible under the form, with a quiet backdrop.
+ crate::term_out::clear_extras(body);
+ let backdrop = if theme::no_color() {
+ Style::default().add_modifier(Modifier::DIM)
+ } else {
+ theme::fg(if light {
+ Color::Rgb(185, 185, 185)
+ } else {
+ Color::Rgb(32, 32, 32)
+ })
+ .bg(theme::depth_fit(if light {
+ Color::Rgb(230, 230, 230)
+ } else {
+ Color::Rgb(4, 4, 4)
+ }))
+ .remove_modifier(Modifier::BOLD | Modifier::REVERSED | Modifier::DIM | Modifier::UNDERLINED)
+ };
+ for y in body.y..body.bottom() {
+ for x in body.x..body.right() {
+ if let Some(c) = buf.cell_mut((x, y)) {
+ c.set_style(backdrop);
+ }
+ }
+ }
+ let side = form.child.is_some() && body.width >= 110;
+ let form_w = if side {
+ ((u32::from(body.width) - 5) * 3 / 5).min(76) as u16
+ } else {
+ body.width.saturating_sub(4).min(76)
+ };
+ let child_w = if side {
+ (body.width - form_w - 5).min(60)
+ } else {
+ form_w
+ };
+ let fields = form.fields();
+ let form_h = (fields.len() as u16 * 2 + 3).min(body.height.saturating_sub(2).max(5));
+ let child_h = form
+ .child
+ .as_ref()
+ .map(|c| if c.kind.editing() { 8 } else { 22 })
+ .unwrap_or(0)
+ .min(body.height.saturating_sub(2).max(5));
+ let total_w = if side { form_w + 2 + child_w } else { form_w };
+ let height = form_h.max(child_h);
+ let x = body.x + (body.width - total_w) / 2;
+ let y = body.y + (body.height - height) / 2;
+ let r = Rect::new(x, y, form_w, form_h);
+ form.area = r;
+ if form.child.is_none() || side || !form.child_active {
+ panel(buf, r, "New Harness", base, border);
+ let gap = if form_h >= fields.len() as u16 * 2 + 3 {
+ 2
+ } else {
+ 1
+ };
+ let capacity = ((form_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 {
+ break;
+ }
+ let active = *field == form.focus;
+ let st = if form.blocked(*field).is_some() {
+ muted
+ } else if active {
+ accent
+ } else {
+ base
+ };
+ let (label, value) = form.describe(*field);
+ put(buf, r.x + 1, fy, 1, if active { "›" } else { " " }, accent);
+ let label_w = if r.width < 45 { 10 } else { 15 };
+ put(
+ buf,
+ r.x + 3,
+ fy,
+ label_w,
+ label,
+ if *field == Field::Create {
+ st.add_modifier(Modifier::BOLD)
+ } else {
+ muted
+ },
+ );
+ put(
+ buf,
+ r.x + 3 + label_w,
+ fy,
+ r.width.saturating_sub(6 + label_w),
+ &value,
+ st,
+ );
+ form.hits
+ .push((Rect::new(r.x + 1, fy, r.width - 2, 1), *field));
+ }
+ let hint = if form.starting {
+ if form.checking {
+ "Checking…"
+ } else {
+ "Starting…"
+ }
+ } else {
+ &form.error
+ };
+ put(
+ buf,
+ r.x + 2,
+ r.bottom() - 2,
+ r.width - 4,
+ hint,
+ if form.error.is_empty() {
+ muted
+ } else {
+ base.patch(theme::fg(theme::DANGER))
+ },
+ );
+ }
+ if !side && !form.child_active {
+ return None;
+ }
+ let Some(c) = &mut form.child else {
+ return None;
+ };
+ let r = Rect::new(if side { x + form_w + 2 } else { x }, y, child_w, child_h);
+ form.child_area = r;
+ panel(buf, r, &c.picker.title, base, border);
+ let query_x = r.x + 4;
+ let query_y = r.y + 2;
+ let query_w = r.width.saturating_sub(6) as usize;
+ put(buf, r.x + 2, query_y, 1, "›", accent);
+ let chars: Vec<_> = c.picker.query.chars().collect();
+ let at = c.picker.qcursor.min(chars.len());
+ let mut from = at;
+ let mut width = 0;
+ while from > 0 && width + chars[from - 1].width().unwrap_or(0) < query_w {
+ from -= 1;
+ width += chars[from].width().unwrap_or(0);
+ }
+ let query: String = chars[from..].iter().collect();
+ put(
+ buf,
+ query_x,
+ query_y,
+ query_w as u16,
+ if query.is_empty() {
+ &c.picker.placeholder
+ } else {
+ &query
+ },
+ if query.is_empty() { muted } else { base },
+ );
+ c.picker.row_at.clear();
+ if !c.kind.editing() {
+ let rows = r.height.saturating_sub(6) as usize;
+ c.picker.page_rows.set(rows as i64);
+ c.picker.scroll = c
+ .picker
+ .scroll
+ .min(c.picker.cursor)
+ .max(c.picker.cursor.saturating_sub(rows.saturating_sub(1)));
+ if c.picker.visible.is_empty() {
+ put(
+ buf,
+ r.x + 3,
+ r.y + 3,
+ r.width - 6,
+ c.picker.busy.as_deref().unwrap_or(&c.picker.empty),
+ muted,
+ );
+ }
+ let mut separator = 0;
+ for (row, (index, _)) in c
+ .picker
+ .visible
+ .iter()
+ .enumerate()
+ .skip(c.picker.scroll)
+ .take(rows)
+ {
+ if c.kind == Choice::Project
+ && c.picker.query.is_empty()
+ && c.picker.rows[*index].id.starts_with("at:")
+ && row > 0
+ && !c.picker.rows[c.picker.visible[row - 1].0]
+ .id
+ .starts_with("at:")
+ {
+ separator = 1;
+ }
+ let at_y = r.y + 4 + (row - c.picker.scroll) as u16 + separator;
+ if at_y >= r.bottom() - 2 {
+ break;
+ }
+ let selected = row == c.picker.cursor;
+ put(
+ buf,
+ r.x + 1,
+ at_y,
+ 1,
+ if selected { "›" } else { " " },
+ accent,
+ );
+ put(
+ buf,
+ r.x + 3,
+ at_y,
+ r.width - 6,
+ &c.picker.rows[*index].label,
+ if c.picker.rows[*index].disabled {
+ muted
+ } else if selected {
+ accent
+ } else {
+ base
+ },
+ );
+ c.picker.row_at.push((at_y, row));
+ }
+ let total = c.picker.visible.len();
+ if total > rows && rows > 0 {
+ let thumb = (rows * rows / total).max(1);
+ let top = (rows - thumb) * c.picker.scroll / (total - rows);
+ for dy in top..top + thumb {
+ put(buf, r.right() - 2, r.y + 4 + dy as u16, 1, "│", muted);
+ }
+ }
+ }
+ let hint = if !form.error.is_empty() {
+ &form.error
+ } else {
+ c.picker.busy.as_deref().unwrap_or("")
+ };
+ put(buf, r.x + 2, r.bottom() - 2, r.width - 4, hint, muted);
+ form.child_active.then(|| {
+ Position::new(
+ query_x + (width as u16).min(r.width.saturating_sub(7)),
+ query_y,
+ )
+ })
+}
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index 35d3109d9..fa72fd114 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -124,6 +124,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) {
if !hidden || speaking { if let Some(pos) = status_line(buf, app, status) { cursor = Some(pos) } }
// A menu is tmux's overlay: over the status line too, where it is kept on the screen.
if let Some(Modal::Menu(m)) = &app.modal { menu(buf, app, m) }
+ if let Some(Modal::NewHarness(form)) = &mut app.modal { cursor = crate::new_harness::draw(buf, body, form); }
if let Some(pos) = cursor { frame.set_cursor_position(pos) }
}
@@ -188,7 +189,7 @@ fn which_key(buf: &mut Buffer, app: &App, body: Rect) {
if digits { items.insert(0, ("0-9".into(), "Select window 0 to 9".into())) }
// The keys a tmux user reaches for every day first (what fits of a small window is those),
// then the rest in the table's order.
- const FIRST: &[&str] = &["c", "n", "p", "l", "0-9", "w", "s", "d", "%", "\"", "x", "z", "o", ";", "[", "]", ":", "?", "&", ",", "$", "!", "q", "t", "{", "}", "Space"];
+ const FIRST: &[&str] = &["c", "N", "n", "p", "l", "0-9", "w", "s", "d", "%", "\"", "x", "z", "o", ";", "[", "]", ":", "?", "&", ",", "$", "!", "q", "t", "{", "}", "Space"];
items.sort_by_key(|(k, _)| FIRST.iter().position(|f| f == k).unwrap_or(FIRST.len()));
let key_w = items.iter().map(|(k, _)| k.width()).max().unwrap_or(1).min(8);
let col_w: usize = key_w + if body.width >= 150 { 44 } else { 32 };
diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjs
index 2c6faf274..c2dffe2d6 100644
--- a/tui/tests/mock-daemon.mjs
+++ b/tui/tests/mock-daemon.mjs
@@ -156,6 +156,7 @@ if (layoutTest && !(port >= 19800 && port <= 19809)) throw new Error('unsafe lay
const layoutFaults = { delays: [], failures: [], writes: [] }
const reconnect = process.env.MOCK_RECONNECT === '1'
if (reconnect && !(port >= 19780 && port <= 19789)) throw new Error('unsafe reconnect test port')
+const creationReceipts = new Map()
const connections = new Map()
const opens = []
const inputs = []
@@ -366,7 +367,16 @@ wss.on('connection', (ws) => {
switch (type) {
case 'agents_list': return reply({ agents: agents[machine].filter((a) => payload.includeStopped || a.status !== 'stopped') })
case 'models_list': return reply({ models: [{ id: 'runtime-v1:x:claude:opus@high', displayName: 'Opus / High' }, { id: 'runtime-v1:x:claude:sonnet@high', displayName: 'Sonnet / High' }] })
- case 'dsh_list': return reply({ dsh: [] })
+ case 'git_project_info': return reply(process.env.MOCK_NEW_UI ? { isGit: !String(payload.path).includes('plain'), branch: 'main', branches: [
+ { ref: 'refs/heads/main', name: 'main', remote: false },
+ { ref: 'refs/heads/feature', name: 'feature', remote: false },
+ { ref: 'refs/heads/already-open', name: 'already-open', remote: false, worktree: '/home/demo/worktrees/already-open' },
+ ] } : { isGit: false })
+ case 'grid_models_list': return reply({ supportsModelLaunch: true, localModelEngines: ['codex', 'claude'], grids: [
+ { name: 'studio', own: true, models: [{ id: 'demo-model', node: 'studio' }] },
+ ] })
+ case 'codex_profiles_list': return reply({ profiles: [{ path: '/home/demo/.codex-work', label: 'Work' }] })
+ case 'dsh_list': return reply({ dsh: process.env.MOCK_NEW_UI ? [{ id: 'example/blender', name: 'Blender', engine: 'codex', engines: ['codex', 'claude'], installed: true }] : [] })
// The agent accounts' limits, as the vendors answer (MOCK_USAGE: Claude's 5-hour window, %).
case 'usage_read': return reply({ providers: [
{ provider: 'claude', account: 'acct-claude', outcome: 'answered', httpStatus: 200, body: { five_hour: { utilization: Number(process.env.MOCK_USAGE || 42), resets_at: '2026-09-26T21:00:00Z' }, seven_day: { utilization: 18, resets_at: '2026-10-01T00:00:00Z' } } },
@@ -382,7 +392,7 @@ wss.on('connection', (ws) => {
const r = a && RECAPS[a.name]
return reply({ agentId: payload.agentId, events: r ? [{ kind: 'summary', recap: r[0], text: r[0] }] : [], asks: r ? [r[1]] : [] })
}
- case 'fs_list_dir': return reply({ path: '/home/demo', entries: [] })
+ case 'fs_list_dir': return reply({ path: process.env.MOCK_NEW_UI ? (payload.path || '/home/demo') : '/home/demo', entries: process.env.MOCK_NEW_UI && !String(payload.path).endsWith('/projects') ? [{ name: 'projects', isDir: true }] : [] })
// What tmux says a pane runs and where (the real daemon asks its tmux; here, fixed).
case 'terminal_info': return reply({ command: 'zsh', path: '/home/demo/src', pid: 4242, tty: '/dev/ttys042' })
// The e2e reads which harnesses were deleted (a killed pane's shell goes with it).
@@ -397,8 +407,38 @@ wss.on('connection', (ws) => {
const rows = turns.map(([ask, answer], turn) => ({ turn, at: Date.now() - (turns.length - turn) * HOUR, ask, answer, tools: turn === 0 ? 'Read src/main.ts\nBash npm test' : '' }))
return reply({ sessionId: payload.sessionId, rows, hasMore: false, total: rows.length, lastAt: x ? x.lastAt : Date.now(), lastAsk: rows[rows.length - 1], ...(x ? { external: { title: x.title, cwd: x.cwd, origin: x.origin, open: x.open } } : {}) })
}
+ case 'agent_create_status': {
+ dial.creationChecks = [...(dial.creationChecks || []), payload]
+ const receipt = creationReceipts.get(`${machine}:${payload.creationId}`)
+ if (receipt?.pendingChecks) { receipt.pendingChecks--; return reply({ creationId: payload.creationId, state: 'pending' }) }
+ return reply({ creationId: payload.creationId, ...(receipt?.outcome || { state: 'missing' }) })
+ }
case 'agent_create': {
dial.created = [...(dial.created || []), payload]
+ const receiptKey = `${machine}:${payload.creationId}`
+ const { requestId: _requestId, creationId: _creationId, ...choices } = payload
+ const fingerprint = JSON.stringify(choices)
+ const previous = creationReceipts.get(receiptKey)
+ if (process.env.MOCK_NEW_UI && previous) {
+ if (previous.fingerprint !== fingerprint) return reply({ error: 'CREATION_CONFLICT' })
+ return reply({ creationId: payload.creationId, ...previous.outcome })
+ }
+ // The daemon's wire contract uses branchMode, not its internal existingBranch flag.
+ if (process.env.MOCK_NEW_UI && payload.branchName === 'feature' && payload.branchMode !== 'existing') {
+ return reply({ error: 'BRANCH_EXISTS', detail: 'Select the existing branch using branchMode.' })
+ }
+ if (process.env.MOCK_NEW_UI === '1' && payload.projectName === 'fail-once') {
+ // The real daemon persists known failures, including a prepared folder.
+ // Reusing this receipt can NEVER make this request succeed.
+ const outcome = { state: 'failed', failure: { code: 'ENGINE_UNAVAILABLE', detail: 'Fixture launch failure' }, preparedFolder: '/home/demo/fail-once' }
+ creationReceipts.set(receiptKey, { fingerprint, outcome })
+ return setTimeout(() => reply({ creationId: payload.creationId, ...outcome }), 150)
+ }
+ if (process.env.MOCK_NEW_UI === '1' && payload.projectName === 'unknown-launch') {
+ const outcome = { state: 'unconfirmed' }
+ creationReceipts.set(receiptKey, { fingerprint, outcome })
+ return reply({ creationId: payload.creationId, ...outcome })
+ }
// Resuming a conversation Harness did not start: refused while it is open elsewhere.
if (payload.resumeSessionId) {
const x = EXTERNAL.find((e) => e.sessionId === payload.resumeSessionId)
@@ -411,6 +451,12 @@ wss.on('connection', (ws) => {
}
const created = agent(randomUUID(), `Mock ${payload.engine}`, payload.engine)
agents[machine].push(created)
+ if (process.env.MOCK_NEW_UI === '1') {
+ const outcome = { state: 'created', agent: created }
+ creationReceipts.set(receiptKey, { fingerprint, outcome, pendingChecks: payload.projectName === 'lose-reply' ? 1 : 0 })
+ if (payload.projectName === 'lose-reply') return ws.terminate()
+ return reply({ creationId: payload.creationId, ...outcome })
+ }
return reply({ agent: created })
}
case 'route_task': {
diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.py
new file mode 100644
index 000000000..14e7a99bf
--- /dev/null
+++ b/tui/tests/new-harness.py
@@ -0,0 +1,260 @@
+#!/usr/bin/env python3
+"""New Harness's real terminal UI, desktop choices, launch payloads and recovery.
+
+Only a private fixture backend, temporary HOME and explicitly named hn/tmux sockets.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import socket
+import subprocess
+import tempfile
+import time
+import urllib.request
+
+ROOT = Path(__file__).resolve().parents[1]
+PORT = int(os.environ.get('HN_NEW_UI_PORT', '19786'))
+assert 19783 <= PORT <= 19789, 'refusing non-test popup port'
+PREFIX = f'hn-new-ui-{os.getpid()}'
+BASE = Path(tempfile.mkdtemp(prefix='hnnu-', dir='/tmp')).resolve()
+HN = BASE / 'hn'
+shutil.copy2(os.environ.get('HN_NEW_UI_BINARY', ROOT / 'target/release/harness-tui'), HN)
+TMUX = shutil.which('tmux')
+assert TMUX
+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}
+ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),
+ TERM='xterm-256color', COLORTERM='truecolor', SHELL='/bin/sh', HARNESS_TUI_DESK='sync',
+ HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', MOCK_DEMO='1', MOCK_RECONNECT='1', MOCK_NEW_UI='1')
+OUTPUT = Path(os.environ['HN_NEW_UI_OUTPUT']) if os.environ.get('HN_NEW_UI_OUTPUT') else None
+if OUTPUT: OUTPUT.mkdir(parents=True, exist_ok=True)
+
+def hn(*args, ok=True):
+ p = subprocess.run([str(HN), '-L', PREFIX, '--port', str(PORT), '-f', '/dev/null', *args],
+ env=ENV, cwd=BASE, text=True, capture_output=True, timeout=12)
+ if ok: assert p.returncode == 0, (args, p.stdout, p.stderr)
+ return p.stdout.strip()
+
+def tmux(*args, ok=True):
+ p = subprocess.run([TMUX, '-L', PREFIX + '-outer', *args], env=ENV, cwd=BASE,
+ text=True, capture_output=True, timeout=10)
+ if ok: assert p.returncode == 0, (args, p.stderr)
+ return p.stdout
+
+def state(route='dial'):
+ with urllib.request.urlopen(f'http://127.0.0.1:{PORT}/test/{route}', timeout=2) as r:
+ result = json.load(r)
+ return result.get('data', result)
+
+def screen(): return tmux('capture-pane', '-p', '-t', 'test')
+def settle_ui():
+ # The form moves when a side chooser opens/closes. Wait for the visible
+ # geometry, not tmux send-keys returning, before taking mouse coordinates.
+ # Crop to popup borders so animated working panes cannot keep it unsettled.
+ previous, changed = None, time.monotonic()
+ deadline = changed + 3
+ while time.monotonic() < deadline:
+ signature = tuple(line[line.index('│'):line.rindex('│') + 1]
+ for line in screen().splitlines() if line.count('│') >= 2)
+ if signature != previous:
+ previous, changed = signature, time.monotonic()
+ elif time.monotonic() - changed >= .15:
+ return
+ time.sleep(.025)
+ raise AssertionError('popup did not settle\n' + screen())
+def keys(*args):
+ tmux('send-keys', '-t', 'test', *args)
+ settle_ui()
+def type_text(text): tmux('send-keys', '-l', '-t', 'test', text)
+def wait(fn, label, seconds=8):
+ end = time.monotonic() + seconds
+ while time.monotonic() < end:
+ if fn(): return
+ time.sleep(.05)
+ raise AssertionError(label + '\n' + screen())
+def shows(text): wait(lambda: text in screen(), text)
+def snapshot(name):
+ time.sleep(.1)
+ if OUTPUT: (OUTPUT / (name + '.ansi')).write_text(tmux('capture-pane', '-p', '-e', '-t', 'test'))
+def create_count(): return len(state().get('created', []))
+def click(x, y):
+ for suffix in ['M', 'm']:
+ raw = f'\x1b[<0;{x+1};{y+1}{suffix}'.encode()
+ tmux('send-keys', '-H', '-t', 'test', *[f'{b:02x}' for b in raw])
+ settle_ui()
+def field(label):
+ def find():
+ for y, line in enumerate(screen().splitlines()):
+ m = re.search(r'│[ ›]*(' + re.escape(label) + r') {2,}', line)
+ if m: return m.start(1), y
+ wait(find, f'field {label}')
+ click(*find())
+def choose_field(label, query):
+ field(label); type_text(query); keys('Enter'); shows('New Harness')
+def new_form():
+ keys('C-b', 'N'); shows('Options')
+def submit(count):
+ # Git discovery is asynchronous. Wait for its answer before accepting the visible draft.
+ time.sleep(.15)
+ keys('Enter')
+ wait(lambda: create_count() == count and 'Options' not in screen(), 'created harness')
+
+def raw(data):
+ tmux('send-keys', '-H', '-t', 'test', *[f'{b:02x}' for b in data.encode()])
+
+mock = None
+started = False
+try:
+ with socket.socket() as probe: probe.bind(('127.0.0.1', PORT))
+ mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)], env=ENV,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ for _ in range(100):
+ assert mock.poll() is None
+ try: state(); break
+ except OSError: time.sleep(.05)
+ else: raise AssertionError('mock startup timeout')
+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',
+ *[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)
+ started = True
+ shows('Fix flaky login test')
+ first_window = hn('display-message', '-p', '#{window_id}')
+ keys('C-b', 'n')
+ wait(lambda: hn('display-message', '-p', '#{window_id}') != first_window, 'lowercase n remains next-window')
+ keys('C-b', 'p'); new_form()
+ snapshot('new-harness-form')
+ before = create_count()
+ input_before = len(state('reconnect')['inputs'])
+ keys('Right'); assert create_count() == before, 'Right on New Harness must not launch'
+ keys('Down'); shows('Search agents and harnesses')
+ assert 'Blender' in screen(), 'the agent chooser appears while moving over Agent'
+ keys('Tab'); snapshot('new-harness-agent')
+ type_text('codex'); keys('Escape')
+ shows('Options'); field('Agent'); type_text('codex'); keys('Enter')
+ field('Project'); shows('Clone Repository'); snapshot('new-harness-project')
+ type_text('clone'); keys('Enter'); shows('Choose a machine'); keys('Enter'); shows('GitHub URL')
+ raw('\x1b[200~autonomous-ai/openharness\x1b[201~'); keys('Enter')
+ shows('Clone: autonomous-ai/openharness')
+ assert create_count() == before, 'choosing fields must not launch'
+ field('Project'); type_text('new folder'); keys('Enter'); shows('Choose a machine'); keys('Enter'); shows('Folder name')
+ type_text('fail-once'); keys('Enter'); shows('New Folder: fail-once')
+ field('Options'); shows('Approvals'); shows('Model'); shows('Profile')
+ assert not re.search(r'│[ ›]*Machine {2,}', screen()), 'Machine belongs in Project, not Options'
+ choose_field('Approvals', 'read only'); shows('Read only')
+ snapshot('new-harness-options')
+ keys('Enter', 'Enter'); shows('Fixture launch failure')
+ assert create_count() == before + 1, 'busy popup prevents double submission'
+ shows('fail-once'); shows('Read only')
+ request = state()['created'][-1]
+ assert request['engine'] == 'codex', request
+ assert request['projectSource'] == 'new' and request['projectName'] == 'fail-once', request
+ assert request['permissionMode'] == 'readOnly' and request['bypassPermission'] is False, request
+ snapshot('new-harness-retry')
+ keys('Escape'); new_form(); shows('Fixture launch failure')
+ submit(before + 2)
+ retry = state()['created'][-1]
+ assert retry['creationId'] != request['creationId'], 'confirmed refusal requires a fresh receipt'
+ assert retry['cwd'] == '/home/demo/fail-once', 'reuse the already prepared folder'
+ assert not any(k in retry for k in ('projectSource', 'projectName', 'gitSource', 'branchRef')), retry
+ assert len(state('reconnect')['inputs']) == input_before, 'form input must never reach a working pane'
+ print('PASS New Harness: desktop fields, keyboard, search, paste, retry and no duplicate/input leak', flush=True)
+
+ new_form(); field('Project'); type_text('open folder'); keys('Enter'); shows('Choose a machine'); keys('Enter'); shows('Use this folder')
+ type_text('projects'); keys('Enter'); shows('Use this folder'); keys('Enter'); shows('/projects')
+ field('Options'); shows('[x]'); choose_field('Branch', 'feature')
+ submit(before + 3)
+ request = state()['created'][-1]
+ assert request['projectSource'] == 'worktree' and request['gitSource'].endswith('/projects'), request
+ assert request['branchRef'] == 'refs/heads/feature' and request['branchMode'] == 'existing', request
+ print('PASS New Harness: browse folders, Git discovery and desktop worktree branch selection', flush=True)
+
+ new_form(); field('Options'); choose_field('Profile', 'Work'); shows('Work')
+ submit(before + 4)
+ assert state()['created'][-1]['codexHome'] == '/home/demo/.codex-work'
+ new_form(); field('Options'); choose_field('Model', 'demo-model'); shows('demo-model')
+ submit(before + 5)
+ request = state()['created'][-1]
+ assert request['gridModel'] == 'demo-model' and request['gridName'] == 'studio', request
+ assert 'codexHome' not in request, request
+ print('PASS New Harness: machine-scoped profiles and explicit model routes', flush=True)
+
+ new_form(); choose_field('Agent', 'Blender'); shows('Choose a coding agent'); type_text('codex'); keys('Enter'); shows('Blender · Codex')
+ submit(before + 6)
+ assert state()['created'][-1]['dsh'] == 'example/blender'
+ new_form(); choose_field('Harness', 'Terminal'); field('Options')
+ assert not re.search(r'│[ ›]*(Model|Approvals|Profile) {2,}', screen()), 'Terminal omits irrelevant settings'
+ # Return focus to the action without accepting any of the disabled Git rows.
+ field('New Harness')
+ wait(lambda: create_count() == before + 7 and 'Options' not in screen(), 'terminal launch')
+ request = state()['created'][-1]
+ assert request['engine'] == 'terminal' and request.get('permissionMode') is None, request
+ assert not any(k in request for k in ('dsh', 'prompt', 'gridModel', 'gitSource', 'codexHome')), request
+ print('PASS New Harness: specialized harness compatibility and ordinary Terminal launch', flush=True)
+
+ 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)]:
+ tmux('resize-window', '-t', 'test', '-x', str(w), '-y', str(h)); time.sleep(.4)
+ 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')
+ wait(lambda: any('Search projects' in line and line.rstrip().endswith('│') for line in screen().splitlines()), 'narrow picker redraw')
+ snapshot('new-harness-narrow')
+ keys('Escape', 'Escape'); assert create_count() == count
+ tmux('resize-window', '-t', 'test', '-x', '150', '-y', '42'); new_form()
+ # Supply actual terminal palette replies, as a light terminal would.
+ raw('\x1b]10;rgb:2020/2020/2020\x1b\\\x1b]11;rgb:ffff/ffff/ffff\x1b\\')
+ snapshot('new-harness-light'); keys('Escape')
+ print('PASS New Harness: draft restoration, narrow/light rendering and cancellation', flush=True)
+
+ new_form(); field('Project'); type_text('new folder'); keys('Enter'); shows('Choose a machine'); keys('Enter'); shows('Folder name')
+ type_text('lose-reply'); keys('Enter'); shows('New Folder: lose-reply')
+ count = create_count()
+ keys('Enter'); shows('Check status'); shows('Launch not confirmed')
+ assert create_count() == count + 1
+ request = state()['created'][-1]
+ # Changes cannot turn a lost reply into another launch, even across dismissal.
+ keys('Down', 'a'); assert 'Search agents' not in screen()
+ keys('Escape'); new_form(); shows('Check status')
+ wait(lambda: any(c['machine'] == request.get('machineId', 'mock0000000000000000000000000001') for c in state('reconnect')['connections']), 'machine reconnected')
+ time.sleep(.5)
+ keys('Enter'); shows('Still starting your harness')
+ assert create_count() == count + 1
+ keys('Enter'); wait(lambda: 'Options' not in screen(), 'original harness recovered')
+ assert create_count() == count + 1, 'status recovery must never send a second create'
+ checks = state()['creationChecks'][-2:]
+ assert len(checks) == 2 and all(c['creationId'] == request['creationId'] for c in checks)
+
+ new_form(); field('Project'); type_text('new folder'); keys('Enter'); shows('Choose a machine'); keys('Enter'); shows('Folder name')
+ type_text('unknown-launch'); keys('Enter'); keys('Enter'); shows('Launch outcome unknown')
+ count = create_count()
+ keys('Enter'); shows('Launch outcome unknown')
+ keys('Escape'); new_form(); shows('Check status')
+ assert create_count() == count
+ keys('Escape')
+ print('PASS New Harness: lost reply, reconnect, pending status and uncertain launch never duplicate', flush=True)
+
+finally:
+ try:
+ if started:
+ hn('kill-server', ok=False); tmux('kill-server', ok=False)
+ def clients():
+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines()
+ return [int(parts[0]) for row in rows if len(parts := row.strip().split(None, 1)) == 2
+ and parts[1].startswith(str(HN) + ' ') and f'-L {PREFIX} ' in parts[1]]
+ for pid in clients():
+ try: os.kill(pid, 15)
+ except ProcessLookupError: pass
+ deadline = time.monotonic() + 5
+ while clients() and time.monotonic() < deadline: time.sleep(.05)
+ assert not clients(), 'New Harness test client did not exit'
+ finally:
+ if mock:
+ mock.terminate()
+ try: mock.wait(timeout=5)
+ except subprocess.TimeoutExpired: mock.kill(); mock.wait()
+ shutil.rmtree(BASE, ignore_errors=True)