The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep New Harness settings visible and add an optional task (#522)
Deeef5d978f9af4
diff --git a/tui/README.md b/tui/README.mdindex 0b7ab6a87..4c360fa34 100644--- a/tui/README.md+++ b/tui/README.md@@ -151,15 +151,18 @@ 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 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 N` `C-b T` | New Harness popup / new terminal. Agent, Project and optional Task sit above Branch, Worktree, Model, Approvals and applicable Profile, with searchable choices. || `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 |-`C-b N` opens the compact desktop-style New Harness form with Agent, Project, collapsed-Options and New Harness. The initial destination is the connected local Harness machine, with successful agent+`C-b N` opens the vertical New Harness form. Agent, Project and optional Task come first,+then a blank row separates Branch, Worktree, Model, Approvals and applicable Profile.+All settings are visible without expanding Options. Project reads `project @ local`, or+`project @ machine` for a remote destination; focusing it shows the full path below.+The initial destination is the connected local Harness machine, with successful agentand 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,+with the displayed choices; Up/Down moves between fields. Enter,Right or typing enters the chooser. Tab switches between the form and chooser; Enter acceptsan item and returns to New Harness. A second Enter starts it in the current window, splittingbeside the focused pane when needed. Lowercase `C-b n` remains next window.@@ -167,11 +170,18 @@ beside the focused pane when needed. Lowercase `C-b n` remains next window.Agent combines coding agents and installed Store harnesses; a Store harness then offers itscompatible coding agents. Project offers Clone Repository, Open Folder, New Folder and recentmachine/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.+a path. Task opens an editor in the same panel: Enter accepts, Alt-Enter inserts a newline,+and pasted tasks retain line breaks. Escape preserves the task in the draft. Supported agents+receive it as their first message; an unavailable first task or one exceeding the daemon's+2,000-character limit is explained before launch. A blank task starts an ordinary session.Git projects default to a new worktree from main, as on desktop; missing main requires a branchchoice. 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+++<sub>Rendered from the isolated terminal fixture in `tests/new-harness.py`.</sub>++Choosers open in the form's place without moving the panel. Escape returns throughnested choosers and preserves a dismissed draft. Confirmed failures keep the draft and reuseany 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 formdiff --git a/tui/docs/new-harness.png b/tui/docs/new-harness.pngnew file mode 100644index 000000000..769134557Binary files /dev/null and b/tui/docs/new-harness.png differdiff --git a/tui/src/keys.rs b/tui/src/keys.rsindex 857145bb7..d89768609 100644--- a/tui/src/keys.rs+++ b/tui/src/keys.rs@@ -153,7 +153,7 @@ impl Keymap {// Harness's own, on keys tmux leaves unbound.// (Enter: the one key to remember — every command and setting by name.)b(k(KeyCode::Enter, none), "choose-command", false, "Commands and settings, by name");- b(ch('N'), "new-harness", false, "New Harness: agent, project and options");+ b(ch('N'), "new-harness", false, "New Harness: agent, project, task and launch settings");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");@@ -622,4 +622,3 @@ mod tmux_parity {assert!(wrong.is_empty(), "keys that differ from tmux 3.5a:\n{}", wrong.join("\n"));}}-diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rsindex b53a2dd58..0e0b98dd7 100644--- a/tui/src/new_harness.rs+++ b/tui/src/new_harness.rs@@ -1,6 +1,7 @@-//! The desktop's compact New Harness form, with a persistent draft and side choosers.+//! New Harness: a keyboard-driven form, with a persistent draft and in-place choosers.mod data;mod receipt;+mod task;pub(crate) use receipt::Creation;mod view;use crate::{@@ -33,6 +34,7 @@ pub struct Draft {pub machine: String,pub what: What,pub project: Project,+ pub task: String,pub permission: String,pub worktree: Option<bool>,pub branch: Option<String>,@@ -45,7 +47,7 @@ pub struct Draft {enum Field {Agent,Project,- Options,+ Task,Model,Approvals,Profile,@@ -73,10 +75,11 @@ enum Choice {Path,Clone,NewFolder,+ Task,}impl Choice {fn editing(&self) -> bool {- matches!(self, Self::Path | Self::Clone | Self::NewFolder)+ matches!(self, Self::Path | Self::Clone | Self::NewFolder | Self::Task)}}struct Child {@@ -94,7 +97,6 @@ pub struct Form {pub attempt: Option<Creation>,prepared_folder: Option<String>,focus: Field,- expanded: bool,child: Option<Child>,child_active: bool,trail: Vec<Child>,@@ -129,18 +131,15 @@ impl Form {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]);+ let mut fields = vec![Field::Agent, Field::Project, Field::Task, Field::Branch, Field::Worktree];+ 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.push(Field::Create);fields@@ -156,7 +155,9 @@ impl Form {&& self.draft.worktree.unwrap_or(true)}fn blocked(&self, field: Field) -> Option<&str> {- if matches!(field, Field::Branch | Field::Worktree) {+ if field == Field::Task && !task::supported(&self.draft.what.engine) && self.draft.task.trim().is_empty() {+ Some("Not available for this agent")+ } else if matches!(field, Field::Branch | Field::Worktree) {if self.git_loading {Some("Checking Git…")} else if self.git["error"].is_string() {@@ -170,9 +171,10 @@ impl Form {None}}- fn project_label(&self) -> String {- let value = match &self.draft.project {- Project::Folder(p) => short_path(p, &self.home),+ fn project_name(&self) -> String {+ match &self.draft.project {+ Project::Folder(p) => p.trim_end_matches('/').rsplit('/').next()+ .filter(|name| !name.is_empty()).unwrap_or("/").into(),Project::New(n) => {if n.is_empty() {"New Folder".into()@@ -181,8 +183,31 @@ impl Form {}}Project::Clone(url) => format!("Clone: {url}"),- };- format!("{}:{value}", self.machine_label)+ }+ }+ fn project_label(&self) -> String {+ format!("{} @ {}", self.project_name(), self.machine_label)+ }+ fn save_task(&mut self) {+ if let Some(c) = &self.child {+ if c.kind == Choice::Task {+ self.draft.task.clone_from(&c.picker.query);+ }+ }+ }+ fn hint(&self) -> String {+ if self.starting { return "Esc close · launch continues".into() }+ if self.attempt.is_some() { return "Enter check status · Esc close".into() }+ if self.focus == Field::Project {+ if let Project::Folder(path) = &self.draft.project {+ return format!("{} @ {}", short_path(path, &self.home), self.machine_label);+ }+ }+ if self.focus == Field::Create {+ "↑/↓ fields · Enter start · Esc close".into()+ } else {+ "↑/↓ fields · Enter choose · Esc back".into()+ }}fn describe(&self, field: Field) -> (&str, String) {let (label, value) = match field {@@ -195,7 +220,11 @@ impl Form {self.draft.what.label.clone(),),Field::Project => ("Project", self.project_label()),- Field::Options => ("Options", if self.expanded { "[-]" } else { "[+]" }.into()),+ Field::Task => ("Task", if self.draft.task.trim().is_empty() {+ "Harness anything… (optional)".into()+ } else {+ self.draft.task.split_whitespace().collect::<Vec<_>>().join(" ")+ }),Field::Model => ("Model",self.draft@@ -273,6 +302,13 @@ fn short_path(path: &str, home: &str) -> String {path.into()}}+fn machine_label(app: &App, machine: &str) -> String {+ if app.fleet.machines.iter().any(|m| m.id == machine && m.local) {+ "local".into()+ } else {+ app.fleet.machine_name(machine)+ }+}fn defaults_path() -> std::path::PathBuf {crate::app::state_dir().join("new-harness.json")}@@ -396,6 +432,7 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {machine: machine.clone(),what,project,+ task: String::new(),permission,worktree: None,branch: None,@@ -412,7 +449,6 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {attempt: None,prepared_folder: None,focus: Field::Create,- expanded: false,child: None,child_active: false,trail: vec![],@@ -437,7 +473,7 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {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.machine_label = machine_label(app, &form.draft.machine);form.home = app.homes.get(&form.draft.machine)@@ -576,8 +612,9 @@ fn project_rows(app: &App, draft: &Draft) -> Vec<Row> {);let mut row = Row::new(format!("at:{machine}\t{}", a.cwd),- format!("{}:{short}", app.fleet.machine_name(machine)),+ format!("{short} @ {}", machine_label(app, machine)),)+ .extra(app.fleet.machine_name(machine)).group("Recent projects");row.disabled = !app.fleet@@ -736,6 +773,7 @@ fn child(app: &mut App, form: &mut Form, kind: Choice, initial: &str) {Choice::Path => "/path/to/project or ~/project",Choice::Clone => "GitHub URL or owner/repository",Choice::NewFolder => "Folder name (optional)",+ Choice::Task => "Harness anything…",};let mut picker = Picker::new("", hint);picker.keep_order = true;@@ -845,6 +883,7 @@ fn load_folder(app: &mut App, form: &mut Form, path: String) {);}fn reveal(app: &mut App, form: &mut Form) {+ form.save_task();form.child = None;form.child_active = false;form.trail.clear();@@ -854,13 +893,15 @@ fn reveal(app: &mut App, form: &mut Form) {let kind = match form.focus {Field::Agent => Choice::Agent,Field::Project => Choice::Project,+ Field::Task => Choice::Task,Field::Model => Choice::Model,Field::Approvals => Choice::Approvals,Field::Profile => Choice::Profile,Field::Branch => Choice::Branch,_ => return,};- child(app, form, kind, "");+ let initial = if kind == Choice::Task { form.draft.task.clone() } else { String::new() };+ child(app, form, kind, &initial);}fn activate(app: &mut App, form: &mut Form) -> bool {form.error.clear();@@ -872,10 +913,6 @@ fn activate(app: &mut App, form: &mut Form) -> bool {}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;@@ -1115,6 +1152,7 @@ fn choose(app: &mut App, form: &mut Form) {set_project(form, Project::Clone(query));}Choice::NewFolder => set_project(form, Project::New(query)),+ Choice::Task => form.draft.task = c.picker.query.clone(),}form.child_active = false;form.trail.clear();@@ -1124,6 +1162,7 @@ fn choose(app: &mut App, form: &mut Form) {sync_git(app, form, false);}fn back(app: &mut App, form: &mut Form) -> bool {+ form.save_task();if form.child_active {if let Some(previous) = form.trail.pop() {form.child = Some(previous);@@ -1172,10 +1211,14 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {return;}let mut launch = false;+ let task_width = form.child_area.width.saturating_sub(6).max(1) as usize;if form.child_active {if let Some(c) = &mut form.child {let editing = c.kind.editing();match key.code {+ KeyCode::Enter if c.kind == Choice::Task && key.modifiers.contains(KeyModifiers::ALT) => {+ c.picker.type_char('\n');+ }KeyCode::Enter => choose(app, &mut form),KeyCode::Tab | KeyCode::BackTab => form.child_active = false,KeyCode::Char('l') if ctrl && matches!(c.kind, Choice::Folder(_)) => {@@ -1187,6 +1230,8 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {let previous = form.child.take().unwrap();step_into(app, &mut form, previous, Choice::Path, &path);}+ KeyCode::Up if c.kind == Choice::Task => task::move_vertical(&mut c.picker, -1, task_width),+ KeyCode::Down if c.kind == Choice::Task => task::move_vertical(&mut c.picker, 1, task_width),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)),@@ -1265,7 +1310,7 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {let field = match ch {'a' => Some(Field::Agent),'p' => Some(Field::Project),- 'o' => Some(Field::Options),+ 't' => Some(Field::Task),_ => None,};if let Some(field) = field {@@ -1277,6 +1322,7 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {_ => {}}}+ form.save_task();if form.child.as_ref()@@ -1295,6 +1341,16 @@ pub fn paste(form: &mut Form, text: &str) {}if let Some(c) = &mut form.child {form.child_active = true;+ if c.kind == Choice::Task {+ let text: String = text.replace("\r\n", "\n").replace('\r', "\n").chars()+ .filter(|ch| *ch == '\n' || *ch == '\t' || !ch.is_control()).collect();+ let at = c.picker.query.char_indices().nth(c.picker.qcursor)+ .map(|(at, _)| at).unwrap_or(c.picker.query.len());+ c.picker.qcursor = c.picker.query[..at].chars().count() + text.chars().count();+ c.picker.query.insert_str(at, &text);+ form.save_task();+ return;+ }let mut line_break = false;for ch in text.chars() {if matches!(ch, '\r' | '\n') {@@ -1336,17 +1392,24 @@ pub fn mouse(app: &mut App, mouse: MouseEvent) {{if let Some(c) = &mut form.child {form.child_active = true;- c.picker.move_by(if mouse.kind == MouseEventKind::ScrollUp {+ let delta = if mouse.kind == MouseEventKind::ScrollUp {-1} else {1- });+ };+ if c.kind == Choice::Task {+ task::move_vertical(&mut c.picker, delta, form.child_area.width.saturating_sub(6).max(1) as usize);+ } else {+ c.picker.move_by(delta as i64);+ }}} 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) {+ if c.kind == Choice::Task {+ task::click(&mut c.picker, form.child_area, pos);+ } else if let Some((_, index)) = c.picker.row_at.iter().find(|(y, _)| *y == mouse.row) {c.picker.cursor = *index;choose(app, &mut form);}@@ -1387,10 +1450,13 @@ pub fn start(app: &mut App) {return;}resolve_launch_machine(app, &mut form);- let fail = if form.git_loading {+ form.save_task();+ let fail = if let Some(error) = task::error(&form.draft.what.engine, &form.draft.task) {+ Some(error)+ } else 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())+ Some("Could not read this project. Choose Branch to retry.".into())} else {form.project_payload().err()};@@ -1475,7 +1541,7 @@ fn launch(app: &mut App, mut form: Box<Form>, visible: bool) {d.machine,d.what,cwd,- None,+ Some(d.task),false,crate::input::NewOpts {extra: Some(extra),@@ -1579,7 +1645,7 @@ mod tests {app}- /// Opening a chooser beside the form (an agent, here) leaves the form where it was, on a wide+ /// Opening a chooser within the form leaves the panel where it was, on a wide/// window and a narrow one.#[tokio::test]async fn the_form_stays_put_when_a_chooser_opens() {@@ -1608,7 +1674,7 @@ mod tests {open(&mut app, explicit, None);let Some(Modal::NewHarness(form)) = &app.modal else { panic!() };assert_eq!(form.draft.machine, "local");- assert_eq!(form.project_label(), "studio:New Folder");+ assert_eq!(form.project_label(), "New Folder @ local");for rows in [modal::machine_rows(&app), modal::new_machine_rows(&app, shell)] {assert_eq!(rows.len(), 1);assert_eq!(rows[0].id, "local");@@ -1625,7 +1691,7 @@ mod tests {let recent: Vec<_> = rows.iter().filter(|r| r.id.starts_with("at:")).collect();assert_eq!(recent.len(), 1);assert_eq!(recent[0].id, "at:local\t/home/dev/repo");- assert_eq!(recent[0].label, "studio:~/repo");+ assert_eq!(recent[0].label, "~/repo @ local");}#[tokio::test]@@ -1649,7 +1715,7 @@ mod tests {refresh(&mut app);let Some(Modal::NewHarness(form)) = &app.modal else { panic!() };assert_eq!(form.draft.machine, if pending { shell } else { "local" });- assert_eq!(form.project_label(), "office:~/repo");+ assert_eq!(form.project_label(), "repo @ local");if pending { assert_eq!(form.attempt.as_ref().unwrap().machine, shell); }}}@@ -1688,6 +1754,37 @@ mod tests {assert!(matches!(app.modal, Some(Modal::Confirm { .. })));}+ #[tokio::test]+ async fn multiline_task_survives_editing_dismissal_and_agent_changes() {+ let mut app = app();+ open(&mut app, None, Some("/home/dev/project".into()));+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ form.focus = Field::Task;+ assert!(!activate(&mut app, &mut form));+ paste(&mut form, "Fix café\r\n\r\nKeep 界 and 🦀 intact.");+ let expected = "Fix café\n\nKeep 界 and 🦀 intact.";+ assert_eq!(form.draft.task, expected);+ key(&mut app, form, KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT));+ let Some(Modal::NewHarness(form)) = app.modal.take() else { panic!() };+ assert_eq!(form.draft.task, format!("{expected}\n"));+ // Escape leaves the editor with its text, then dismisses the draft.+ key(&mut app, form, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));+ let Some(Modal::NewHarness(form)) = app.modal.take() else { panic!() };+ key(&mut app, form, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));+ open(&mut app, None, None);+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ assert_eq!(form.draft.task, format!("{expected}\n"));+ set_engine(&mut form, "terminal");+ assert!(task::error(&form.draft.what.engine, &form.draft.task).is_some());+ assert!(form.blocked(Field::Task).is_none(), "a retained task can still be cleared");+ set_engine(&mut form, "claude");+ reveal(&mut app, &mut form);+ assert_eq!(form.child.as_ref().unwrap().picker.query, format!("{expected}\n"));+ choose(&mut app, &mut form);+ assert_eq!(form.focus, Field::Create);+ assert_eq!(form.draft.task, format!("{expected}\n"));+ }+#[tokio::test]async fn the_form_is_the_panel_centered_and_anchored_at_every_terminal_size() {let mut app = app();@@ -1701,11 +1798,12 @@ mod tests {for height in [1, 4, 5, 10, 14, 24, 42] {let area = Rect::new(3, 2, width, height);let mut anchor = None;- for expanded in [false, true, false] {- form.expanded = expanded;- for chooser in [None, Some(Choice::Agent), Some(Choice::Clone), None] {+ for engine in ["claude", "codex", "terminal"] {+ set_engine(&mut form, engine);+ for chooser in [None, Some(Choice::Agent), Some(Choice::Clone), Some(Choice::Task), None] {if let Some(kind) = chooser {- child(&mut app, &mut form, kind, "");+ let text = if kind == Choice::Task { "A long task with 界 and 🦀.\n".repeat(50) } else { String::new() };+ child(&mut app, &mut form, kind, &text);} else {form.child = None;}@@ -1724,16 +1822,14 @@ mod tests {let left = form.area.x - area.x;let right = area.right() - form.area.right();assert!(left.abs_diff(right) <= 1, "not centered in {area:?}");- if !expanded {- let top = form.area.y - area.y;- let bottom = area.bottom() - form.area.bottom();- assert!(top.abs_diff(bottom) <= 1, "not centered in {area:?}");- }+ let top = form.area.y - area.y;+ let bottom = area.bottom() - form.area.bottom();+ assert!(top.abs_diff(bottom) <= 1, "not centered in {area:?}");let position = (form.area.x, form.area.y, form.area.width);assert_eq!(*anchor.get_or_insert(position),position,- "form moved in {area:?}: expanded={expanded}, active={active}"+ "form moved in {area:?}: engine={engine}, active={active}");assert_eq!(form.area.intersection(area), form.area);}@@ -1748,6 +1844,31 @@ mod tests {}}+ #[tokio::test]+ async fn terminal_resize_before_its_input_event_keeps_the_form_and_choosers_in_frame() {+ for choice in [None, Some(Choice::Agent), Some(Choice::Task)] {+ let mut app = app();+ open(&mut app, None, None);+ if let Some(kind) = choice {+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ child(&mut app, &mut form, kind, "");+ app.modal = Some(Modal::NewHarness(form));+ }+ // The backend has already resized, but no Resize input event has been delivered.+ for (width, height) in [(80, 24), (45, 14), (22, 5), (1, 1), (150, 42)] {+ let mut terminal = ratatui::Terminal::new(+ ratatui::backend::TestBackend::new(width, height),+ ).unwrap();+ terminal.draw(|frame| crate::ui::draw(frame, &mut app)).unwrap();+ let bounds = Rect::new(0, 0, width, height);+ let Some(Modal::NewHarness(form)) = &app.modal else { panic!() };+ assert_eq!(form.area.intersection(bounds), form.area);+ assert_eq!(form.child_area.intersection(bounds), form.child_area);+ assert!(form.hits.iter().all(|(hit, _)| hit.intersection(bounds) == *hit));+ }+ }+ }+#[tokio::test]async fn project_error_keeps_its_recovery_instruction_and_action_visible() {let mut app = app();@@ -1783,7 +1904,6 @@ mod tests {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");diff --git a/tui/src/new_harness/data.rs b/tui/src/new_harness/data.rsindex 4cfa87038..b9d988f3c 100644--- a/tui/src/new_harness/data.rs+++ b/tui/src/new_harness/data.rs@@ -147,7 +147,7 @@ pub fn project_payload(d: &Draft, info: &Value) -> Result<(Option<String>, Valuelet 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());+ return Err("Choose a branch, or turn Worktree off".into());}let Some(reference) = reference else {return Ok((Some(folder.clone()), extra));@@ -250,6 +250,7 @@ mod tests {label: "Codex".into(),},project: Project::Folder("/home/dev/repo".into()),+ task: String::new(),permission: "auto".into(),worktree: None,branch: None,diff --git a/tui/src/new_harness/task.rs b/tui/src/new_harness/task.rsnew file mode 100644index 000000000..2a934d4d7--- /dev/null+++ b/tui/src/new_harness/task.rs@@ -0,0 +1,226 @@+//! The optional first task, edited in the same panel as the form's other choices.+use super::*;++// Keep these aligned with cli/src/lib/engineLaunch.ts and desktop/lib/core/first_task.dart.+const MAX_LENGTH: usize = 2000;++pub(super) fn supported(engine: &str) -> bool {+ matches!(engine, "claude" | "codex" | "opencode" | "hermes")+}++pub(super) fn error(engine: &str, text: &str) -> Option<String> {+ let text = text.trim();+ if text.is_empty() {+ None+ } else if !supported(engine) {+ Some("This agent cannot start with a task. Clear Task or choose another agent.".into())+ } else if text.encode_utf16().count() > MAX_LENGTH {+ Some(format!(+ "Task is too long. Shorten it to {MAX_LENGTH} characters."+ ))+ } else {+ None+ }+}++struct Line {+ start: usize,+ text: String,+}++fn char_width(ch: char) -> usize {+ if ch == '\t' {+ 4+ } else {+ ch.width().unwrap_or(0)+ }+}++fn lines(text: &str, width: usize) -> Vec<Line> {+ let width = width.max(1);+ let mut lines = vec![Line {+ start: 0,+ text: String::new(),+ }];+ let mut col = 0;+ for (at, ch) in text.chars().enumerate() {+ if ch == '\n' {+ lines.push(Line {+ start: at + 1,+ text: String::new(),+ });+ col = 0;+ continue;+ }+ let w = char_width(ch);+ if col > 0 && col + w > width {+ lines.push(Line {+ start: at,+ text: String::new(),+ });+ col = 0;+ }+ lines.last_mut().unwrap().text.push(ch);+ col += w;+ }+ // Leave a cell for the insertion cursor after a completely full final line.+ if col >= width {+ lines.push(Line {+ start: text.chars().count(),+ text: String::new(),+ });+ }+ lines+}++fn position(lines: &[Line], cursor: usize) -> (usize, usize) {+ let row = lines+ .iter()+ .rposition(|line| line.start <= cursor)+ .unwrap_or(0);+ let col = lines[row]+ .text+ .chars()+ .take(cursor.saturating_sub(lines[row].start))+ .map(char_width)+ .sum();+ (row, col)+}++fn at_column(line: &Line, col: usize) -> usize {+ let mut width = 0;+ let mut at = line.start;+ for ch in line.text.chars() {+ let w = char_width(ch);+ if width + w > col {+ break;+ }+ width += w;+ at += 1;+ }+ at+}++pub(super) fn move_vertical(picker: &mut Picker, delta: isize, width: usize) {+ let lines = lines(&picker.query, width);+ let (row, col) = position(&lines, picker.qcursor);+ let to = (row as isize + delta).clamp(0, lines.len() as isize - 1) as usize;+ if row != to {+ picker.qcursor = at_column(&lines[to], col)+ }+}++fn text_area(r: Rect) -> Rect {+ let top = if r.height >= 8 { 4 } else { 1 };+ Rect::new(+ r.x + 3,+ r.y + top,+ r.width.saturating_sub(6).max(1),+ r.height.saturating_sub(top + 2).max(1),+ )+}++pub(super) fn click(picker: &mut Picker, panel: Rect, pos: Position) {+ let r = text_area(panel);+ if !r.contains(pos) {+ return;+ }+ let lines = lines(&picker.query, r.width as usize);+ let row = (picker.scroll + (pos.y - r.y) as usize).min(lines.len() - 1);+ picker.qcursor = at_column(&lines[row], (pos.x - r.x) as usize);+}++pub(super) fn draw(+ buf: &mut Buffer,+ panel: Rect,+ picker: &mut Picker,+ error: &str,+ base: Style,+ muted: Style,+ accent: Style,+) -> Position {+ let r = text_area(panel);+ if panel.height >= 8 {+ view::put(buf, r.x, panel.y + 2, r.width, "Task (optional)", muted);+ let count = format!(+ "{}/{}",+ picker.query.trim().encode_utf16().count(),+ MAX_LENGTH+ );+ let width = count.width() as u16;+ if r.width >= width + 18 {+ view::put(buf, r.right() - width, panel.y + 2, width, &count, muted);+ }+ }+ let lines = lines(&picker.query, r.width as usize);+ let (row, col) = position(&lines, picker.qcursor);+ picker.scroll = picker+ .scroll+ .min(row)+ .max(row.saturating_sub(r.height as usize - 1));+ if picker.query.is_empty() {+ view::put(buf, r.x, r.y, r.width, &picker.placeholder, muted);+ } else {+ for (dy, line) in lines+ .iter()+ .skip(picker.scroll)+ .take(r.height as usize)+ .enumerate()+ {+ view::put(+ buf,+ r.x,+ r.y + dy as u16,+ r.width,+ &line.text.replace('\t', " "),+ base,+ );+ }+ }+ let y = r.y + (row - picker.scroll) as u16;+ view::put(buf, panel.x + 1, y, 1, "›", accent);+ view::put(+ buf,+ panel.x + 2,+ panel.bottom() - if panel.height >= 5 { 2 } else { 1 },+ panel.width.saturating_sub(4),+ if error.is_empty() {+ "Enter done · Alt-Enter newline · Esc back"+ } else {+ error+ },+ if error.is_empty() {+ muted+ } else {+ base.patch(theme::fg(theme::DANGER))+ },+ );+ Position::new(r.x + (col as u16).min(r.width - 1), y)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn first_task_validation_preserves_text_and_matches_wire_length() {+ assert!(error("terminal", " ").is_none());+ assert!(error("cursor", "Fix login").is_some());+ assert!(error("codex", &"🦀".repeat(1000)).is_none());+ assert!(error("claude", &"🦀".repeat(1001)).is_some());+ assert!(error("claude", &format!("\n{}\n", "x".repeat(MAX_LENGTH))).is_none());+ }++ #[test]+ fn wrapped_task_navigation_tracks_unicode_and_hard_breaks() {+ let mut p = Picker::new("", "");+ p.query = "ab界cd\nnext".into();+ p.qcursor = 3;+ move_vertical(&mut p, 1, 5);+ assert_eq!(p.qcursor, 5);+ move_vertical(&mut p, 1, 5);+ assert_eq!(p.qcursor, 7);+ let lines = lines("界界", 4);+ assert_eq!(position(&lines, 2), (1, 0));+ }+}diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rsindex 3354bfcb5..930912b8d 100644--- a/tui/src/new_harness/view.rs+++ b/tui/src/new_harness/view.rs@@ -24,7 +24,7 @@ fn error_lines(text: &str, width: usize) -> Vec<String> {lines}-fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) {+pub(super) fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) {if width == 0 {return;}@@ -47,7 +47,9 @@ fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) {}/// The form's surface, as the settings panel draws its own: filled, no border.-fn panel(buf: &mut Buffer, r: Rect, base: Style) { crate::settings::fill(buf, r, base) }+fn panel(buf: &mut Buffer, r: Rect, base: Style) {+ crate::settings::fill(buf, r, base)+}pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {form.hits.clear();@@ -65,7 +67,13 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {return None;}// The settings panel's colours, and its quiet backdrop over the working panes.- let crate::settings::Chrome { base, muted, accent, backdrop, .. } = crate::settings::chrome();+ let crate::settings::Chrome {+ base,+ muted,+ accent,+ backdrop,+ ..+ } = crate::settings::chrome();crate::settings::backdrop(buf, body, backdrop);// The form is the menus' panel: centred, the one size whatever is open — and a chooser (an// agent, a machine, a folder…) opens in its place, as a section of Appearance does, so@@ -80,21 +88,33 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {form.area = r;if form.child.is_none() || side || !form.child_active {panel(buf, r, base);- let fields_h = form_h - error_h + 1;let error_y = r.bottom() - 1 - error_h;- let gap = if fields_h >= fields.len() as u16 * 2 + 3 {- 2- } else {- 1- };- let capacity = ((fields_h.saturating_sub(5) / gap) + 1) as usize;- let focus = fields.iter().position(|f| *f == form.focus).unwrap_or(0);- let skip = focus.saturating_sub(capacity - 1);- for (row, field) in fields.iter().skip(skip).take(capacity).enumerate() {- let fy = r.y + if form_h < 5 { 0 } else { 2 } + row as u16 * gap;- if fy >= error_y {- break;- }+ let fields_y = r.y + if form_h < 5 { 0 } else { 2 };+ let capacity = error_y.saturating_sub(fields_y);+ let mut row: u16 = 0;+ let rows: Vec<_> = fields+ .iter()+ .map(|field| {+ // One blank line between the task and settings, and before the launch action.+ if matches!(field, Field::Branch | Field::Create) {+ row += 1;+ }+ let at = row;+ row += 1;+ (at, field)+ })+ .collect();+ let focus = rows+ .iter()+ .find(|(_, field)| **field == form.focus)+ .map(|(row, _)| *row)+ .unwrap_or(0);+ let skip = focus.saturating_sub(capacity.saturating_sub(1));+ for (row, field) in rows+ .into_iter()+ .filter(|(row, _)| *row >= skip && *row < skip + capacity)+ {+ let fy = fields_y + row - skip;let active = *field == form.focus;let st = if form.blocked(*field).is_some() {muted@@ -110,7 +130,11 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {buf,r.x + 3,fy,- label_w,+ if *field == Field::Create {+ r.width.saturating_sub(6)+ } else {+ label_w+ },label,if *field == Field::Create {st.add_modifier(Modifier::BOLD)@@ -118,20 +142,57 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {muted},);- put(- buf,- r.x + 3 + label_w,- fy,- r.width.saturating_sub(6 + label_w),- &value,- st,- );+ let value_width = r.width.saturating_sub(6 + label_w);+ let value_x = r.x + 3 + label_w;+ if *field == Field::Project {+ // Keep the destination visible even when the project name must be shortened.+ let suffix = format!(" @ {}", form.machine_label);+ let suffix_width = suffix.width() as u16;+ if value_width > suffix_width + 2 {+ let name = form.project_name();+ let name_width = (name.width() as u16).min(value_width - suffix_width);+ put(buf, value_x, fy, name_width, &name, st);+ put(buf, value_x + name_width, fy, suffix_width, &suffix, st);+ } else {+ put(+ buf,+ value_x,+ fy,+ value_width,+ &format!("@ {}", form.machine_label),+ st,+ );+ }+ } else {+ put(+ buf,+ value_x,+ fy,+ value_width,+ &value,+ if *field == Field::Task && form.draft.task.is_empty() && !active {+ muted+ } else {+ st+ },+ );+ }form.hits.push((Rect::new(r.x + 1, fy, r.width - 2, 1), *field));}- for (row, line) in errors.iter().take(error_h as usize).enumerate() {- put(buf, r.x + 2, error_y + row as u16, r.width - 4, line,- base.patch(theme::fg(theme::DANGER)));+ if form.error.is_empty() {+ put(buf, r.x + 2, error_y, r.width - 4, &form.hint(), muted);+ } else {+ for (row, line) in errors.iter().take(error_h as usize).enumerate() {+ put(+ buf,+ r.x + 2,+ error_y + row as u16,+ r.width - 4,+ line,+ base.patch(theme::fg(theme::DANGER)),+ );+ }}}if !side && !form.child_active {@@ -143,6 +204,17 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {let r = Rect::new(if side { x + form_w + 2 } else { x }, y, child_w, child_h);form.child_area = r;panel(buf, r, base);+ if c.kind == Choice::Task {+ return Some(task::draw(+ buf,+ r,+ &mut c.picker,+ &form.error,+ base,+ muted,+ accent,+ ));+ }let query_x = r.x + 4;let query_y = r.y + 2;let query_w = r.width.saturating_sub(6) as usize;diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 2bac423e5..7a918636b 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -165,6 +165,12 @@ pub fn draw(frame: &mut Frame, app: &mut App) {crate::term_out::begin_frame(usstyle, links);let area = frame.area();if area.width == 0 || area.height == 0 { return }+ // Ratatui can observe a resize before the queued terminal event reaches the app.+ // Every pane and popup must use this frame's dimensions before drawing into its buffer.+ if app.size != (area.width, area.height) {+ app.size = (area.width, area.height);+ app.fit_panes();+ }// The status lines (tmux's status: off, on, 2 … 5), at the bottom or (status-position) the top.let lines = app.status_lines().max(1).min(area.height);let status = Rect::new(0, if app.status_top { 0 } else { area.height - lines }, area.width, lines);diff --git a/tui/tests/fresh-user-journeys.py b/tui/tests/fresh-user-journeys.pyindex f155b35db..155bbaecf 100644--- a/tui/tests/fresh-user-journeys.py+++ b/tui/tests/fresh-user-journeys.py@@ -28,7 +28,6 @@ def repository(u, name, branch='main', committed=True):def options(u):- u.field('Options')u.wait('Worktree')diff --git a/tui/tests/fresh-user.py b/tui/tests/fresh-user.pyindex 5f84799ea..ff5fc41a0 100644--- a/tui/tests/fresh-user.py+++ b/tui/tests/fresh-user.py@@ -127,7 +127,7 @@ class User:def form(self, engine=None):self.keys('C-b', 'N')- self.wait('Options')+ self.wait('Task')if engine:self.choose('Agent', engine, 'Search agents')@@ -147,7 +147,7 @@ class User:self.wait('Folder name' if action == 'new folder' else 'GitHub URL')self.text(value)self.keys('Enter')- self.wait('Options')+ self.wait('Task')def launch(self, engine, label, double_enter=False, click_create=False):before = {s['id'] for s in self.status()['sessions']}@@ -158,7 +158,7 @@ class User:added = self.check(lambda: [s for s in self.status()['sessions'] if s['id'] not in before],'A new harness should become available', 180)assert len(added) == 1 and added[0]['engine'] == engine, added- self.check(lambda: not re.search(r'(?<![^\s│›])Options {2,}', self.screen()), 'Form closes after launch')+ self.check(lambda: not re.search(r'(?<![^\s│›])Task {2,}', self.screen()), 'Form closes after launch')self.zoom()markers = {'codex': ['Welcome to Codex'],'claude': ['Choose the text style', 'Select login method'],diff --git a/tui/tests/local-shells.py b/tui/tests/local-shells.pyindex 5eb37ecee..125228a74 100644--- a/tui/tests/local-shells.py+++ b/tui/tests/local-shells.py@@ -35,7 +35,7 @@ HOME = BASE / 'home'HOME.mkdir()HN = BASE / 'hn'shutil.copy2(SOURCE, HN)-ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'USER', 'LOGNAME', 'TZ') if k in os.environ}+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'USER', 'LOGNAME', 'TZ', 'NODE_PATH') if k in os.environ}ENV.update(HOME=str(HOME), PORT=str(PORT), HN_SOCKET_NAME=PREFIX, HN_TMPDIR=str(BASE), SHELL='/bin/sh',TERM='xterm-256color', HNE_REMOVE='bad', HNE_KEEP='bad', HNE_HIDDEN='bad')CONF = BASE / 'tmux.conf'@@ -189,9 +189,9 @@ try:wait(lambda: hn('display-message', '-p', '#{local_machine}|#{pane_machine}').stdout.strip() == 'mock-local|mock-local','local shell and status share the machine name from the app')tm('send-keys', '-t', 'outer', 'C-b', 'N')- wait(lambda: 'mock-local:' in tm('capture-pane', '-p', '-t', 'outer').stdout, 'New Harness uses the app machine name')+ wait(lambda: ' @ local' in tm('capture-pane', '-p', '-t', 'outer').stdout, 'New Harness identifies the local destination')tm('send-keys', '-t', 'outer', 'Escape')- print('PASS daemon arrival preserves local shell and uses the app machine name everywhere', flush=True)+ print('PASS daemon arrival preserves local shell and identifies the local destination', flush=True)hn('kill-server', check=False)wait(lambda: not own_processes(), 'all test hn processes stop')diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.pyindex d5816da36..217ab2fcb 100644--- a/tui/tests/new-harness.py+++ b/tui/tests/new-harness.py@@ -24,8 +24,9 @@ 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 = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ', 'NODE_PATH') if k in os.environ}ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),+ RUST_BACKTRACE='1',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@@ -52,12 +53,18 @@ def screen(): return tmux('capture-pane', '-p', '-t', 'test')def settle_ui():# Wait for chooser content to redraw, not just tmux send-keys returning,# before taking mouse coordinates.- # Crop to popup borders so animated working panes cannot keep it unsettled.+ # The panel is borderless; crop inside its central 90% surface so animated+ # working panes around it cannot keep it unsettled.previous, changed = None, time.monotonic()deadline = changed + 3while time.monotonic() < deadline:- signature = tuple(line[line.index('│'):line.rindex('│') + 1]- for line in screen().splitlines() if line.count('│') >= 2)+ lines = screen().splitlines()+ # Once the form/chooser closes, live panes are allowed to keep changing.+ if not any('›' in line for line in lines):+ return+ width = max(map(len, lines), default=0)+ padx, pady = width // 20 + 2, len(lines) // 20 + 2+ signature = tuple(line[padx:width-padx] for line in lines[pady:len(lines)-pady])if signature != previous:previous, changed = signature, time.monotonic()elif time.monotonic() - changed >= .15:@@ -77,7 +84,9 @@ def wait(fn, label, seconds=8):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'))+ if OUTPUT:+ (OUTPUT / (name + '.ansi')).write_text(tmux('capture-pane', '-p', '-e', '-t', 'test'))+ (OUTPUT / (name + '.txt')).write_text(screen())def create_count(): return len(state().get('created', []))def click(x, y):for suffix in ['M', 'm']:@@ -86,7 +95,7 @@ def click(x, y):settle_ui()def field_at(label):# A field's label: after a space, the pointer or an edge (the form is a borderless panel).- return r'(?<![^\s│›])(' + label + r') {2,}'+ return r'(?<![^\s│›])(' + label + r')(?= {2,}|$)'def field(label):def find():for y, line in enumerate(screen().splitlines()):@@ -96,8 +105,9 @@ def field(label):click(*find())def choose_field(label, query):field(label); type_text(query); keys('Enter'); shows('New Harness')+def form_visible(): return re.search(field_at('Task'), screen()) is not Nonedef new_form():- keys('C-b', 'N'); shows('Options')+ keys('C-b', 'N'); wait(form_visible, 'New Harness form')def placement():window, windows, panes = hn('display-message', '-p', '#{window_id} #{session_windows} #{window_panes}').split()return window, int(windows), int(panes)@@ -111,7 +121,7 @@ def submit(count):time.sleep(.15)before = placement()keys('Enter')- wait(lambda: create_count() == count and 'Options' not in screen(), 'created harness')+ wait(lambda: create_count() == count and not form_visible(), 'created harness')placed_in_current_window(before)def raw(data):@@ -149,7 +159,7 @@ try:assert 'Blender' in screen(), 'the agent chooser lists the harnesses'snapshot('new-harness-agent')type_text('codex'); keys('Escape')- shows('Options'); field('Agent'); type_text('codex'); keys('Enter')+ shows('Approvals'); 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')@@ -157,10 +167,16 @@ try: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(field_at('Machine'), screen()), 'Machine belongs in Project, not Options'+ shows('Approvals'); shows('Model'); shows('Profile')+ assert not re.search(field_at('Options|Machine'), screen()), 'settings are direct fields; machine belongs in Project'choose_field('Approvals', 'read only'); shows('Read only')- snapshot('new-harness-options')+ task_text = 'Fix café login.\n\nKeep 界 and 🦀 intact.\nAdd a regression test.'+ field('Task'); shows('Task (optional)')+ raw('\x1b[200~Fix café login.\r\n\r\nKeep 界 and 🦀 intact.\x1b[201~')+ shows('Keep 界 and 🦀 intact.')+ keys('M-Enter'); type_text('Add a regression test.'); keys('Enter')+ assert create_count() == before, 'accepting a task returns to the form without launching'+ snapshot('new-harness-settings')keys('Enter', 'Enter'); shows('Fixture launch failure')assert create_count() == before + 1, 'busy popup prevents double submission'shows('fail-once'); shows('Read only')@@ -168,6 +184,7 @@ try:assert request['engine'] == 'codex', requestassert request['projectSource'] == 'new' and request['projectName'] == 'fail-once', requestassert request['permissionMode'] == 'readOnly' and request['bypassPermission'] is False, request+ assert request['prompt'] == task_text, requestsnapshot('new-harness-retry')keys('Escape'); new_form(); shows('Fixture launch failure')submit(before + 2)@@ -175,22 +192,23 @@ try: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 retry['prompt'] == task_text, 'retry retains the complete task'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')+ type_text('projects'); keys('Enter'); shows('Use this folder'); keys('Enter'); shows('projects @ local')+ shows('[x]'); choose_field('Branch', 'feature')submit(before + 3)request = state()['created'][-1]assert request['projectSource'] == 'worktree' and request['gitSource'].endswith('/projects'), requestassert request['branchRef'] == 'refs/heads/feature' and request['branchMode'] == 'existing', requestprint('PASS New Harness: browse folders, Git discovery and desktop worktree branch selection', flush=True)- new_form(); field('Options'); choose_field('Profile', 'Work'); shows('Work')+ new_form(); 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')+ new_form(); 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@@ -201,19 +219,19 @@ try:new_form(); field('Agent'); type_text('Blender'); keys('Enter'); 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')+ new_form(); choose_field('Harness', 'Terminal')assert not re.search(field_at('Model|Approvals|Profile'), screen()), 'Terminal omits irrelevant settings'# Return focus to the action without accepting any of the disabled Git rows.before_terminal = placement()field('New Harness')- wait(lambda: create_count() == before + 7 and 'Options' not in screen(), 'terminal launch')+ wait(lambda: create_count() == before + 7 and not form_visible(), 'terminal launch')placed_in_current_window(before_terminal)request = state()['created'][-1]assert request['engine'] == 'terminal' and request.get('permissionMode') is None, requestassert not any(k in request for k in ('dsh', 'prompt', 'gridModel', 'gitSource', 'codexHome')), requestprint('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')+ new_form(); field('Agent'); type_text('claude'); keys('Enter'); 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)] * 3:@@ -222,10 +240,34 @@ try: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')+ shows('Search projects')snapshot('new-harness-narrow')keys('Escape', 'Escape'); assert create_count() == counttmux('resize-window', '-t', 'test', '-x', '150', '-y', '42'); new_form()++ # A review capture with the requested project label, through the real folder chooser.+ choose_field('Approvals', 'auto-approve')+ field('Project'); type_text('open folder'); keys('Enter'); shows('Choose a machine'); keys('Enter'); shows('Use this folder')+ keys('C-l', 'C-a', 'C-k'); type_text('/home/dev/autonomous-harness'); keys('Enter')+ shows('Use this folder'); keys('Enter')+ shows('autonomous-harness @ local'); shows('[x]')+ tmux('resize-window', '-t', 'test', '-x', '100', '-y', '26'); settle_ui()+ snapshot('new-harness-flat')+ field('Task'); shows('Task (optional)')+ raw('\x1b[200~Improve the New Harness keyboard flow.\nKeep the launch settings visible.\x1b[201~')+ shows('Keep the launch settings visible.'); snapshot('new-harness-task')+ keys('Escape', 'Escape'); new_form(); shows('Improve the New Harness keyboard flow.')+ snapshot('new-harness-flat-task')+ tmux('resize-window', '-t', 'test', '-x', '80', '-y', '24'); settle_ui()+ snapshot('new-harness-flat-narrow')+ # Clearing the task allows an unsupported engine; it must never silently discard one.+ choose_field('Agent', 'Terminal'); field('New Harness'); shows('This agent cannot start with a task')+ assert create_count() == count, 'an unsupported task is rejected before creating a harness'+ field('Task'); keys('C-a', 'C-k', 'Enter'); choose_field('Agent', 'claude')+ field('Task'); type_text('x' * 2001); keys('Enter'); field('New Harness'); shows('Task is too long')+ assert create_count() == count, 'an overlong task is rejected before creating a harness'+ field('Task'); keys('C-a', 'C-k', 'Enter')+ tmux('resize-window', '-t', 'test', '-x', '150', '-y', '42'); settle_ui()# 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')@@ -245,7 +287,7 @@ try: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')+ keys('Enter'); wait(lambda: not form_visible(), 'original harness recovered')placed_in_current_window(before_recovery)assert create_count() == count + 1, 'status recovery must never send a second create'checks = state()['creationChecks'][-2:]