The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(tui): unify pane control, machine names, and workspace behavior (#489)
Deec6da5c64a831
diff --git a/tui/README.md b/tui/README.mdindex 457150d14..b63b6e632 100644--- a/tui/README.md+++ b/tui/README.md@@ -48,8 +48,8 @@ this computer unless you name it); the others are this computer's, kept between**More than one terminal** works as with one tmux server. Each `hn` is a client. `hn attach -tmain` from a second terminal (or over SSH) shows `main` in both, as tmux does: a split, a new-window or a window chosen in either shows in both, and either can type into its panes (the first-key takes the pane's keyboard). `attach -r` only watches; `attach -d` takes the session and+window or a window chosen in either shows in both, and either can type into its panes (typing+into a watcher takes control across that TUI's tabs). `attach -r` only watches; `attach -d` takes the session anddetaches the others. Commands from a shell reach every session, whichever terminal has it. `hnls`, `list-clients` and `detach-client -a` see them all, and nothing is lost when they detach inany order: the last one showing a session keeps it. What tmux's server@@ -79,10 +79,10 @@ Splits, `resize-pane`, the seven layouts, `swap-pane`, `rotate-window`, `join-paand `select-pane` are tmux 3.5a's own arithmetic (layout.c, window.c): the same split sizes, the samepane numbers and the same active pane after each. hn draws these layouts as pane surfaceswith one-cell gaps and inset terminal content. Panes have no drawn borders: background-contrast identifies focus. The focused pane keeps the terminal's native background across the-whole surface. Inactive dark panes use `rgb(64, 64, 64)` with softer text, separated by dark gaps.-A lone or zoomed pane keeps the same focused surface and surrounding canvas. Light terminals-keep a light counterpart.+contrast identifies focus. The margins and gaps keep the terminal's native background. The focused+pane uses a subtly contrasting fill (`#181818` on a black terminal), while inactive dark panes use+`rgb(64, 64, 64)` with softer text. A lone or zoomed pane keeps the same focused surface. Light+terminals keep a light counterpart.Explicit pane-border styles still customize the title; border line choices apply in classic andtmux appearances.Explicit program colors and user styles stay intact. The muted green status bar has a continuous@@ -105,9 +105,16 @@ fleet counts, the quoted local machine name and clock sit on the right. The githeader, aligned to the right with its PR and written `⎇ branch` without redundant punctuation.Status-bar groups are separated by two spaces, with one space at each outer edge to alignwith the pane surfaces. Window tabs start at the left, without a machine/session label.-The right side shows the machine running hn by its name in the app, such as `"office"`,-falling back to its hostname, independent of the focused pane or session name.+Local and remote machines use their names from the app everywhere, such as `"office"`.+Local shell panes keep that same name across daemon disconnects and reconnects. Unnamed account+machines use `machine-<id8>`, as on desktop and phone; before this computer is known, it is+`This computer`. The status bar names the machine running hn, independent of the focused pane+or session name.Custom status formats and the prefix cue remain supported.+Take Control (`C-b : take-control`, or `take`) reclaims all available local and remote panes+across the TUI's tabs, including hidden ones, without changing focus. Typing into a watched pane+does the same; the input goes only to that pane. Reconnects keep watching until a person asks+for control again, and read-only clients keep their read-only behavior.One key differs on purpose: ⇧⏎reaches the pane as `CSI 13;2u` (a new line in an agent's prompt; tmux, without `extended-keys`,sends a plain Enter).@@ -140,11 +147,12 @@ Harness's own, only on keys tmux leaves unbound (every tmux key does what tmux d| `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 local machine, with successful agent+Options and New Harness. The initial destination is the connected local Harness machine, with successful agentand project choices remembered. Explicit project commands keep their destination. Enter startswith 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.+an item and returns to New Harness. A second Enter starts it in the current window, splitting+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 recent@@ -260,7 +268,7 @@ has multiple accounts, extra remote accounts say `Claude@studio 20%` to distinguand Codex; Grok and other providers are not listed until a quota source is available. Existing`usage`, `usage_high` and `usage_high_mark` formats retain their used-quota meaning for customconfigurations. Other formats:-`#{local_machine}` (this computer's name in the app, falling back to its hostname),+`#{local_machine}` (this computer's name in the app),`#{pane_machine}` (the focused pane's machine), `#{pane_far}` (another machine's), `#{pane_watched}` and `#{pane_watcher}`(another window has the pane to type in, and who), and `#{waiting}` (the harnesses waiting onyou).@@ -347,7 +355,9 @@ are sitting at, over SSH too.## Two windows, one harnessA terminal has one keyboard. Opening a harness another window is driving shows it read-only-("watching"); the first key you type takes it over, and the other window starts watching.+("watching"); taking control here reclaims this TUI's panes across all tabs, and the other+window starts watching. The first key typed into a watcher also takes control, preserving that+key for its intended pane.## The dialdiff --git a/tui/docs/panes.png b/tui/docs/panes.pngindex a72b30cf1..b663994ce 100644Binary files a/tui/docs/panes.png and b/tui/docs/panes.png differdiff --git a/tui/src/app.rs b/tui/src/app.rsindex 7d71234a1..d4f8c1194 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -1111,8 +1111,9 @@ impl App {}if id.is_empty() { return }app.fleet.local_id = id.clone();+ for machine in &mut app.fleet.machines { machine.local = machine.id == id || crate::local::is_local(&machine.id); }if app.fleet.machine(&id).is_none() {- app.fleet.machines.insert(0, Machine { id: id.clone(), name: hostname(), local: true, status: "running".into(), reach: Reach::Unknown });+ app.fleet.machines.insert(0, Machine { id: id.clone(), name: fleet::machine_display_name(&id, None), local: true, status: "running".into(), reach: Reach::Unknown });}app.connect(&id);app.refresh_machines();@@ -1150,7 +1151,7 @@ impl App {fn ensure_local_shells(&mut self) {if self.fleet.machine(crate::local::MACHINE).is_none() {- self.fleet.machines.insert(0, Machine { id: crate::local::MACHINE.into(), name: hostname(), local: true, status: "running".into(), reach: Reach::Unknown });+ self.fleet.machines.insert(0, Machine { id: crate::local::MACHINE.into(), name: "This computer".into(), local: true, status: "running".into(), reach: Reach::Unknown });}self.connect(crate::local::MACHINE);}@@ -1172,10 +1173,10 @@ impl App {for row in rows {let id = row.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();if id.is_empty() { continue }- let name = ["name", "hostname"].iter().filter_map(|k| row.get(*k).and_then(Value::as_str)).map(str::trim).find(|s| !s.is_empty()).unwrap_or(&id[..8.min(id.len())]).to_string();+ let name = fleet::machine_display_name(&id, row.get("name").and_then(Value::as_str));let status = row.get("status").and_then(Value::as_str).unwrap_or("unknown").to_string();match app.fleet.machine_mut(&id) {- Some(machine) => { machine.name = name; machine.status = status }+ Some(machine) => { machine.name = name; machine.status = status; machine.local = id == local }None => app.fleet.machines.push(Machine { local: id == local, id: id.clone(), name, status, reach: Reach::Unknown }),}}@@ -1272,12 +1273,13 @@ impl App {for pane in self.panes.values_mut().filter(|p| p.machine_id == machine_id) {pane.stream = None;pane.opening = false;+ pane.takeover_pending = false;pane.open_token += 1;if !matches!(pane.phase, Phase::Card { .. }) {pane.phase = if needs_link {Phase::Card { title: "This machine is not linked here".into(), detail: format!("Link it once with its remote password (machines, then C-l), or run:\nharness link connect {machine_id}"), keys: vec![("enter".into(), "retry".into()), (self.keymap.hint("choose-tree -m").unwrap_or_default(), "machines".into())] }} else {- Phase::Connecting(format!("Reconnecting to {}…", self.fleet.machines.iter().find(|m| m.id == machine_id).map(|m| m.name.clone()).unwrap_or_default()))+ Phase::Connecting(format!("Reconnecting to {}…", self.fleet.machine_name(&machine_id)))};}pane.dirty = true;@@ -1661,6 +1663,26 @@ impl App {}}+ /// A user asks for control of this TUI: reclaim every available pane across its tabs and+ /// sessions without moving focus. Reconnects and ownership notifications never call this.+ pub fn take_control(&mut self) {+ if self.read_only() { return }+ let mut ids: Vec<u64> = self.tabs.iter().chain(self.sessions.iter()+ .filter(|s| !s.mirror.as_ref().is_some_and(|m| m.readonly))+ .flat_map(|s| s.tabs.iter())).flat_map(Tab::panes).collect();+ ids.sort_unstable();+ ids.dedup();+ for id in ids {+ let Some(pane) = self.panes.get_mut(&id) else { continue };+ if pane.dead.is_some() || matches!(pane.phase, Phase::Card { .. }) { continue }+ if pane.stream.is_some() && !pane.read_only && !matches!(pane.phase, Phase::Watching(_)) { continue }+ if !self.fleet.machine(&pane.machine_id).is_some_and(Machine::usable)+ || !self.links.get(&pane.machine_id).is_some_and(|s| s.link.is_some()) { continue }+ if pane.opening { pane.takeover_pending = true }+ else { self.open_stream(id, true) }+ }+ }+/// Open (or re-open) a pane's terminal. [takeover]: take the keyboard from any other window.pub fn open_stream(&mut self, pane_id: u64, takeover: bool) {let content = self.content_size(pane_id);@@ -1700,7 +1722,7 @@ impl App {// recognised by this token and not allowed to overwrite the current state.pane.open_token += 1;let token = pane.open_token;- let host = hostname();+ let host = self.fleet.local_machine_name();self.spawn(async move {link.request("terminal_open", json!({"protocolVersion": 3,@@ -1728,6 +1750,7 @@ impl App {}let Some(pane) = self.panes.get_mut(&pane_id) else { return };pane.opening = false;+ let takeover_requested = std::mem::take(&mut pane.takeover_pending);match reply {Ok((ty, payload)) if ty == "terminal_ready" => {pane.stream = stream;@@ -1739,7 +1762,8 @@ impl App {pane.phase = if pane.read_only {Phase::Watching(payload.get("heldBy").and_then(|h| h.get("name")).and_then(Value::as_str).unwrap_or("another window").to_string())} else { Phase::Live };- let queued = std::mem::take(&mut pane.queued);+ let retake = takeover_requested && pane.read_only;+ let queued = if retake { Vec::new() } else { std::mem::take(&mut pane.queued) };let read_only = pane.read_only;// The tile changed size while this was opening: tell the far pane now.if !read_only && pane.want != asked {@@ -1761,6 +1785,9 @@ impl App {let death = stream.and_then(|id| self.orphan_exits.remove(&id).map(|(_, death)| death)).or_else(|| serde_json::from_value::<pane::Exit>(payload["exit"].clone()).ok());if let Some(death) = death { self.local_ended(pane_id, death) }}+ if retake && self.panes.get(&pane_id).is_some_and(|p| p.dead.is_none() && matches!(p.phase, Phase::Watching(_))) {+ self.open_stream(pane_id, true);+ }}Ok((_, payload)) => {let code = payload.get("code").and_then(Value::as_str).unwrap_or("TERMINAL_OPEN_FAILED").to_string();@@ -2191,8 +2218,7 @@ impl App {fn machine_session_name(&self) -> String {// (Before the daemon has said which it is, this computer as the fleet was last seen:// `hn attach -t studio` finds the desk's session at once.)- let m = if self.fleet.local_id.is_empty() { self.fleet.machines.iter().find(|m| m.local) } else { self.fleet.machine(&self.fleet.local_id) };- m.map(|m| m.name.clone()).filter(|n| !n.is_empty()).unwrap_or_else(hostname)+ self.fleet.local_machine_name()}fn stash_name(&self, s: &Stash) -> String { s.alias.clone().unwrap_or_else(|| self.machine_session_name()) }@@ -5735,6 +5761,79 @@ mod recovery_tests {app}+ #[tokio::test]+ async fn taking_control_reclaims_hidden_local_and_remote_panes_without_moving_focus() {+ let mut app = fixture();+ app.fleet.machines[0].local = true;+ app.fleet.local_id = "test-peer".into();+ app.fleet.machines.push(Machine { id: "other-peer".into(), name: "Remote".into(), local: false, status: "running".into(), reach: Reach::Ready });+ app.links.insert("other-peer".into(), LinkState { link: Some(Link::spawn(app.port, "other-peer", 1, app.sink.clone())), generation: 1, attempts: 0, retry_at: None });+ let mut controlled = Pane::new(5, "test-peer", "already-controlled", 80, 24);+ controlled.stream = Some(Uuid::new_v4());+ controlled.phase = Phase::Live;+ let stream = controlled.stream;+ app.panes.insert(5, controlled);+ app.tabs = (1..=5).map(|id| {+ let mut tab = Tab::with_wid("Control test", id);+ tab.root = Some(Node::new(id, 80, 23));+ tab.focus = Some(id);+ tab+ }).collect();+ app.active = 1;+ for id in [1, 2, 4] {+ let pane = app.panes.get_mut(&id).unwrap();+ pane.phase = Phase::Watching("another app".into());+ pane.read_only = true;+ }+ app.client_flags.push("read-only".into());+ app.take_control();+ assert!(![1, 2, 4].iter().any(|id| app.panes[id].opening));+ app.client_flags.clear();+ app.take_control();+ for id in [1, 2, 4] {+ assert!(app.panes[&id].opening);+ assert_eq!(app.panes[&id].open_token, 8);+ }+ assert!(matches!(app.panes[&3].phase, Phase::Card { .. }));+ assert_eq!(app.panes[&5].stream, stream);+ assert_eq!(app.active, 1);+ assert_eq!(app.focused(), Some(2));+ app.take_control();+ for id in [1, 2, 4] { assert_eq!(app.panes[&id].open_token, 8); }+ for state in app.links.values() { state.link.as_ref().unwrap().close(); }+ }++ #[tokio::test]+ async fn taking_control_during_a_passive_open_preserves_input_and_claims_once() {+ let mut app = fixture();+ app.tabs[0].root = Some(Node::new(1, 80, 23));+ app.tabs[0].focus = Some(1);+ let pane = app.panes.get_mut(&1).unwrap();+ pane.phase = Phase::Watching("another app".into());+ pane.read_only = true;+ pane.opening = true;+ pane.stream = None;+ pane.queued.push(b"hello".to_vec());+ app.take_control();+ assert!(app.panes[&1].takeover_pending);+ assert_eq!(app.panes[&1].open_token, 7);+ app.opened(1, "test-peer", 7, (80, 24), Ok(("terminal_ready".into(), json!({"streamId":Uuid::new_v4().to_string(),"readOnly":true}))));+ assert!(app.panes[&1].opening);+ assert!(!app.panes[&1].takeover_pending);+ assert_eq!(app.panes[&1].open_token, 8);+ assert_eq!(app.panes[&1].queued, [b"hello".to_vec()]);+ app.opened(1, "test-peer", 8, (80, 24), Ok(("terminal_ready".into(), json!({"streamId":Uuid::new_v4().to_string(),"readOnly":false}))));+ assert!(matches!(app.panes[&1].phase, Phase::Live));+ assert!(app.panes[&1].queued.is_empty());+ app.take_control();+ assert_eq!(app.panes[&1].open_token, 8);+ // A passive watcher response with no new gesture must never retake a terminal.+ app.opened(2, "test-peer", 7, (80, 24), Ok(("terminal_ready".into(), json!({"streamId":Uuid::new_v4().to_string(),"readOnly":true}))));+ assert!(matches!(app.panes[&2].phase, Phase::Watching(_)));+ assert!(!app.panes[&2].opening);+ app.links["test-peer"].link.as_ref().unwrap().close();+ }+#[tokio::test]async fn expired_lease_recovers_hidden_shells_and_ignores_cancelled_events() {let mut app = fixture();diff --git a/tui/src/cli.rs b/tui/src/cli.rsindex 88cbe851f..fa927dc3e 100644--- a/tui/src/cli.rs+++ b/tui/src/cli.rs@@ -291,7 +291,11 @@ async fn offline(port: u16, args: &[String], name: Option<&str>) -> i32 {if !doc.get("sessions").map(Value::is_array).unwrap_or(false) { doc["sessions"] = json!([]) }// The desk's session: named as it was, else for this computer; its windows the desk's tabs.let (local, list) = machines(port).await.unwrap_or_default();- let machine_name = list.iter().find(|(id, _, _)| *id == local).map(|(_, n, _)| n.clone()).unwrap_or_else(crate::app::hostname);+ let machine_name = list.iter().find(|(id, _, _)| *id == local).map(|(_, n, _)| n.clone()).unwrap_or_else(|| {+ let mut fleet = crate::fleet::Fleet::default();+ fleet.load_cache();+ fleet.local_machine_name()+ });let rows = doc["sessions"].as_array().cloned().unwrap_or_default();let desk_row = rows.iter().find(|r| r.get("desk").and_then(Value::as_bool).unwrap_or(false));let desk_name = desk_row.and_then(|r| r.get("name").and_then(Value::as_str)).map(str::to_string).unwrap_or(machine_name);@@ -405,10 +409,10 @@ pub(crate) async fn machines(port: u16) -> Result<(String, Vec<(String, String,let status = http_json(port, "GET", "/api/status", None).await.map_err(|e| format!("the daemon is not running ({e}) — harness start"))?;let local = status.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();let reply = http_json(port, "GET", "/api/machines", None).await.unwrap_or(json!({}));- let mut out = vec![(local.clone(), crate::app::hostname(), true)];+ let mut out = vec![(local.clone(), crate::fleet::machine_display_name(&local, None), true)];for row in reply.get("machines").and_then(Value::as_array).cloned().unwrap_or_default() {let id = row.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();- let name = ["name", "hostname"].iter().filter_map(|k| row.get(*k).and_then(Value::as_str)).find(|s| !s.trim().is_empty()).unwrap_or(&id).to_string();+ let name = crate::fleet::machine_display_name(&id, row.get("name").and_then(Value::as_str));// This computer by the name the fleet (and the status line) gives it.if id == local { out[0].1 = name; continue }if id.is_empty() { continue }diff --git a/tui/src/commands.rs b/tui/src/commands.rsindex 62710858c..6a53e4597 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -85,6 +85,7 @@ pub const COMMANDS: &[(&str, &str, &str)] = &[("confirm-before", "confirm", "Ask y/n before a command"),("new-harness", "newh", "New harness: [engine] [@machine] [folder] — or choose"),("new-terminal", "newt", "A shell on this pane's machine"),+ ("take-control", "take", "Reclaim control of all panes across the TUI's tabs"),("clone-harness", "cloneh", "A second harness with this one's history"),("restart-harness", "restarth", "Restart this harness"),("pause-harness", "pauseh", "Pause this harness (the conversation is kept)"),@@ -1302,7 +1303,7 @@ fn harness_target(app: &App, words: &Words) -> Result<Option<(String, String)>,fn find_harness(app: &App, t: &str) -> Result<(String, String), String> {if let Some((m, a)) = t.split_once(':') {if app.fleet.agent(m, a).is_some() { return Ok((m.to_string(), a.to_string())) }- if let Some(machine) = app.fleet.machines.iter().find(|x| x.name == m) { if app.fleet.agent(&machine.id, a).is_some() { return Ok((machine.id.clone(), a.to_string())) } }+ if let Some(machine) = app.fleet.machines.iter().find(|x| app.fleet.machine_name(&x.id) == m && app.fleet.agent(&x.id, a).is_some()) { return Ok((machine.id.clone(), a.to_string())) }}if let Some(a) = app.fleet.agents.values().find(|a| a.id == t) { return Ok(a.key()) }if t.starts_with('%') || t.contains([':', '.']) {@@ -3479,6 +3480,7 @@ fn run_words_in(app: &mut App, words: &[String]) {}"new-harness" => { if words.len() < 2 { input::run(app, "new") } else { input::new_harness_words(app, &words[1..]) } }"new-terminal" => input::run(app, "terminal"),+ "take-control" => app.take_control(),// A harness's verbs, on -t's harness (the hook's in a harness-* hook), else the focused// pane's; from a shell -t is needed, and one mid-turn is restarted or paused only with -y// (the keys ask first).diff --git a/tui/src/fleet.rs b/tui/src/fleet.rsindex 40da846b5..e74017975 100644--- a/tui/src/fleet.rs+++ b/tui/src/fleet.rs@@ -430,10 +430,40 @@ pub struct Fleet {pub agents: HashMap<(String, String), Agent>,}+/// Match the desktop and phone: the app's saved name, or its stable machine-id label.+pub fn machine_display_name(id: &str, name: Option<&str>) -> String {+ name.map(str::trim).filter(|name| !name.is_empty()).map(str::to_string)+ .unwrap_or_else(|| format!("machine-{}", id.chars().take(8).collect::<String>()))+}+impl Fleet {pub fn machine(&self, id: &str) -> Option<&Machine> { self.machines.iter().find(|m| m.id == id) }pub fn machine_mut(&mut self, id: &str) -> Option<&mut Machine> { self.machines.iter_mut().find(|m| m.id == id) }- pub fn machine_name(&self, id: &str) -> String { self.machine(id).map(|m| m.name.clone()).unwrap_or_default() }+ /// The account's record for this computer; the local PTY transport is not another machine.+ pub fn registered_local_machine(&self) -> Option<&Machine> {+ self.machine(&self.local_id).filter(|m| !crate::local::is_local(&m.id))+ .or_else(|| self.machines.iter().find(|m| m.local && !crate::local::is_local(&m.id)))+ }+ pub fn local_machine_name(&self) -> String {+ self.registered_local_machine().map(|m| machine_display_name(&m.id, Some(&m.name)))+ .unwrap_or_else(|| "This computer".into())+ }+ pub fn machine_name(&self, id: &str) -> String {+ if crate::local::is_local(id) { return self.local_machine_name() }+ machine_display_name(id, self.machine(id).map(|m| m.name.as_str()))+ }+ /// New work from a local shell goes through Harness when its daemon is connected.+ /// Existing PTYs keep their transport identity so their sessions survive reconnects.+ pub fn launch_machine_id<'a>(&'a self, id: &'a str) -> &'a str {+ if crate::local::is_local(id) {+ if let Some(machine) = self.registered_local_machine().filter(|m| m.usable()) { return &machine.id }+ }+ id+ }+ pub fn visible_machines(&self) -> impl Iterator<Item = &Machine> {+ let connected_local = self.registered_local_machine().is_some_and(Machine::usable);+ self.machines.iter().filter(move |m| !connected_local || !crate::local::is_local(&m.id))+ }pub fn agent(&self, machine: &str, id: &str) -> Option<&Agent> { self.agents.get(&(machine.to_string(), id.to_string())) }pub fn state_of(&self, agent: &Agent) -> State { agent.state(self.machine(&agent.machine_id)) }@@ -567,6 +597,34 @@ pub fn ago(ms: u64) -> String {#[cfg(test)]mod tests {use super::*;++ #[test]+ fn local_shells_share_the_app_name_without_changing_their_transport() {+ let shell = crate::local::MACHINE;+ let mut fleet = Fleet { local_id: "registered-local".into(), ..Default::default() };+ for (id, name, local) in [(shell, "m0", true), ("registered-local", "office", true), ("remote", "GPU rig", false)] {+ fleet.machines.push(Machine { id: id.into(), name: name.into(), local, status: "running".into(), reach: Reach::Ready });+ }+ assert_eq!(fleet.machine_name(shell), "office");+ assert_eq!(fleet.machine_name("registered-local"), "office");+ assert_eq!(fleet.machine_name("remote"), "GPU rig");+ assert_eq!(fleet.launch_machine_id(shell), "registered-local");+ assert_eq!(fleet.visible_machines().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["registered-local", "remote"]);+ assert_eq!(fleet.machine(shell).unwrap().id, shell);+ // A rename is visible even to existing shell panes. Offline boot keeps the cached app name.+ fleet.machine_mut("registered-local").unwrap().name = "Work Mac".into();+ assert_eq!(fleet.machine_name(shell), "Work Mac");+ fleet.local_id = shell.into();+ fleet.machine_mut("registered-local").unwrap().reach = Reach::Offline;+ assert_eq!(fleet.local_machine_name(), "Work Mac");+ assert_eq!(fleet.machine_name(shell), "Work Mac");+ assert_eq!(fleet.launch_machine_id(shell), shell);+ // An unnamed account machine follows the desktop/phone convention, not its hostname.+ fleet.machine_mut("registered-local").unwrap().name.clear();+ assert_eq!(fleet.machine_name(shell), "machine-register");+ assert_eq!(Fleet::default().machine_name(shell), "This computer");+ }+#[test]fn parses_iso() {assert_eq!(parse_iso("1970-01-01T00:00:01.500Z"), Some(1500));diff --git a/tui/src/format.rs b/tui/src/format.rsindex 26fcadc10..87e6782c6 100644--- a/tui/src/format.rs+++ b/tui/src/format.rs@@ -1054,7 +1054,7 @@ fn quota_warning<'a>(readings: impl Iterator<Item = &'a crate::fleet::Usage>, ma}pub fn pane_title(app: &App, window: usize, pane: u64) -> String {- let Some(p) = app.panes.get(&pane) else { return crate::app::hostname() };+ let Some(p) = app.panes.get(&pane) else { return app.fleet.local_machine_name() };let tab_id = app.tabs.get(window).map(|t| t.id.clone()).unwrap_or_default();if !p.osc_title.is_empty() && app.options.get("allow-set-title", &tab_id, Some(pane)).as_deref() == Some("on") { return p.osc_title.clone() }if !p.title.is_empty() { return p.title.clone() }@@ -1065,8 +1065,8 @@ pub fn pane_title(app: &App, window: usize, pane: u64) -> String {return if p.machine_id == app.fleet.local_id { crate::app::full_hostname() } else { app.fleet.machine_name(&p.machine_id) };}// A harness not heard of yet (another terminal's new one, before the list comes): what runs- // in it, else tmux's own title (the host) — never its id.- agent.map(|a| a.name.clone()).or_else(|| p.fg_command.clone()).unwrap_or_else(|| if p.machine_id == app.fleet.local_id { crate::app::full_hostname() } else { app.fleet.machine_name(&p.machine_id) })+ // in it, else the machine's app name.+ agent.map(|a| a.name.clone()).or_else(|| p.fg_command.clone()).unwrap_or_else(|| app.fleet.machine_name(&p.machine_id))}/// Keep a distinguishing suffix, such as "(3)", visible when a title is long.@@ -1288,8 +1288,7 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V"host" => crate::app::full_hostname(),"host_short" => crate::app::full_hostname().split('.').next().unwrap_or("").to_string(),// This computer's name in Harness, including app renames; never the focused pane's.- "local_machine" => app.fleet.machine(&app.fleet.local_id).or_else(|| app.fleet.machines.iter().find(|m| m.local))- .map(|m| m.name.clone()).filter(|name| !name.is_empty()).unwrap_or_else(crate::app::full_hostname),+ "local_machine" => app.fleet.local_machine_name(),// Harness's own: the machine a pane is on, and how many harnesses wait on you."machine" => pane.map(|p| app.fleet.machine_name(&p.machine_id)).unwrap_or_default(),"waiting" => app.fleet.waiting().to_string(),diff --git a/tui/src/input.rs b/tui/src/input.rsindex 4896d3a37..80b488735 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -209,20 +209,22 @@ fn on_key(app: &mut App, key: KeyEvent) {}}-/// Keys into the focused pane. A watcher is promoted first — typing is how you take a terminal.+/// Keys into the focused pane. Typing in a watcher takes control across the TUI.fn send_to_focused(app: &mut App, bytes: Vec<u8>) {let Some(focus) = app.focused() else { return };send_to_pane(app, focus, bytes)}-/// Keys into a pane (send-keys -t): a watcher's is taken over first, as typing takes it.+/// Keys into a pane (send-keys -t): a watcher first reclaims the TUI's other panes too.pub fn send_to_pane(app: &mut App, focus: u64, bytes: Vec<u8>) {// attach -r: a session only watched takes no keys.if app.read_only() && app.tabs.iter().any(|t| t.panes().contains(&focus)) { return }let Some(pane) = app.panes.get_mut(&focus) else { return };if pane.read_only || matches!(pane.phase, Phase::Watching(_)) || pane.stream.is_none() {pane.queued.push(bytes);- if !pane.opening { app.open_stream(focus, true) }+ app.take_control();+ // A popup has no tab, so its own stream still needs to be opened here.+ if app.panes.get(&focus).is_some_and(|p| !p.opening) { app.open_stream(focus, true) }return;}// synchronize-panes (window_pane_key): the same keys into every other pane of the window that@@ -649,8 +651,8 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {}PickerKind::Machines => {picker.set_rows(modal::machine_rows(app));- let up = app.fleet.machines.iter().filter(|m| m.usable()).count();- picker.status = format!("{up}/{} connected", app.fleet.machines.len());+ let up = app.fleet.visible_machines().filter(|m| m.usable()).count();+ picker.status = format!("{up}/{} connected", app.fleet.visible_machines().count());picker.hints = vec![("enter", "its harnesses"), ("M-n", "new there"), ("C-t", "terminal there"), ("M-l", "link")];}PickerKind::Layout => { picker.set_rows(modal::layout_rows()); picker.hints = vec![("enter", "apply")] }@@ -845,7 +847,7 @@ pub fn run(app: &mut App, command: &str) {}"restart" => agent_rpc(app, "agent_restart", "Restarted"),"pause" => agent_rpc(app, "agent_delete", "Paused — the conversation is saved"),- "take" => { if let Some(f) = app.focused() { app.open_stream(f, true) } }+ "take" => app.take_control(),"rename" => {let Some((machine, agent)) = focused_agent(app) else { return };let name = app.fleet.agent(&machine, &agent).map(|a| a.name.clone()).unwrap_or_default();@@ -1262,6 +1264,7 @@ fn create(app: &mut App, machine: String, what: What, cwd: Option<String>, messafn 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()) }pub(crate) fn create_opts(app: &mut App, machine: String, what: What, cwd: Option<String>, message: Option<String>, worktree: bool, opts: NewOpts) {+ let machine = app.fleet.launch_machine_id(&machine).to_string();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 });@@ -1317,14 +1320,22 @@ fn creation_finished(app: &mut App, machine: String, session: u32, opts: NewOptsif 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.+ // Keep new harnesses in the current window, filling it or splitting beside+ // the focused pane; -d keeps the previous pane focused.let back = (app.session_id, app.tab().id.clone());let swapped = session != app.session_id && app.swap_back.is_none() && app.sessions.iter().any(|s| s.id == session) && { app.swap_back = Some(back.0); app.swap_session(session) };- let before = app.tab().id.clone();- let placement = if app.tab().root.is_none() { Placement::Auto(None) } else { Placement::Tab };- app.open_agent(&machine, id, placement);- if opts.detached { if let Some(i) = app.tabs.iter().position(|t| t.id == before) { app.select_tab(i) } }+ let before = (app.tab().id.clone(), app.focused(), app.tab().zoomed);+ app.open_agent(&machine, id, Placement::Auto(None));+ if opts.detached {+ if let Some(i) = app.tabs.iter().position(|t| t.id == before.0) {+ app.select_tab(i);+ if let Some(pane) = before.1.filter(|p| app.tabs[i].panes().contains(p)) {+ app.focus_pane(i, pane);+ app.tabs[i].zoomed = before.2;+ app.fit_panes();+ }+ }+ }if let Some(fmt) = opts.print.as_ref().and(app.print_new.take()) {let line = app.find_pane(&machine, id).map(|(w, p)| crate::format::spans_for_pane(app, &fmt, w, p, ratatui::style::Style::default()).into_iter().map(|s| s.content.into_owned()).collect::<String>()).unwrap_or_default();if let Some(tx) = app.held_reply.take() { let _ = tx.send((vec![line], Vec::new(), 0)); }@@ -3000,7 +3011,8 @@ pub fn new_harness_words(app: &mut App, words: &[String]) {}flags = false;if let Some(m) = w.strip_prefix('@').filter(|_| task.is_empty()) {- match app.fleet.machines.iter().find(|x| x.name.to_lowercase().starts_with(&m.to_lowercase()) || x.id == m) { Some(x) => machine = x.id.clone(), None => return app.error(format!("can't find machine: {m}")) }+ let matched = app.fleet.visible_machines().find(|x| app.fleet.machine_name(&x.id).to_lowercase().starts_with(&m.to_lowercase()) || x.id == m).map(|x| x.id.clone());+ match matched { Some(id) => machine = id, None => return app.error(format!("can't find machine: {m}")) }} else if task.is_empty() && (w.starts_with('/') || w.starts_with('~') || w.starts_with("./") || w.starts_with("../") || w == ".") {cwd = Some(path(app, &machine, &w));} else if task.is_empty() && engine.is_none() && (theme::engine_label(&w) != w || w == "terminal") {@@ -3109,6 +3121,54 @@ pub fn menu_mouse(app: &mut App, m: &crate::mouse::Event) {mod tests {use super::*;+ #[tokio::test]+ async fn created_harness_stays_in_the_current_window() {+ for existing in 0..=2 {+ for detached in [false, true] {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (150, 42));+ for index in 0..existing {+ app.open_agent("fixture", &format!("existing-{index}"), Placement::Auto(None));+ }+ let window = app.tab().id.clone();+ let panes = app.tab().panes();+ let focus = app.focused();+ app.tab_mut().zoomed = existing > 1;+ let session = app.session_id;+ creation_finished(&mut app, "fixture".into(), session,+ NewOpts { detached, ..Default::default() },+ Ok(json!({"agent":{"id":"created", "name":"New harness", "engine":"codex"}})), false);+ assert_eq!(app.tabs.len(), 1, "creation must not add a window");+ assert_eq!(app.tab().id, window);+ assert_eq!(app.tab().panes().len(), existing + 1);+ assert!(panes.iter().all(|p| app.tab().panes().contains(p)));+ let (_, created) = app.find_pane("fixture", "created").unwrap();+ assert_eq!(app.focused(), if detached { focus.or(Some(created)) } else { Some(created) });+ assert_eq!(app.tab().zoomed, detached && existing > 1);+ }+ }+ }++ #[tokio::test]+ async fn created_harness_reuses_the_home_window() {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (150, 42));+ let window = app.tab().id.clone();+ app.tab_mut().home = true;+ app.open_agent("fixture", "home-shell", Placement::Fill(window.clone()));+ assert!(app.tab().home);+ let session = app.session_id;+ creation_finished(&mut app, "fixture".into(), session, NewOpts::default(),+ Ok(json!({"agent":{"id":"created", "name":"New harness", "engine":"codex"}})), false);+ assert_eq!(app.tabs.len(), 1);+ assert_eq!(app.tab().id, window);+ assert_eq!(app.tab().panes().len(), 1);+ assert!(!app.tab().home);+ assert!(app.find_pane("fixture", "home-shell").is_none());+ let (_, created) = app.find_pane("fixture", "created").unwrap();+ assert_eq!(app.focused(), Some(created));+ }+#[tokio::test]async fn delayed_picker_refresh_preserves_the_replacement_modal() {let (sink, _) = tokio::sync::mpsc::unbounded_channel();diff --git a/tui/src/main.rs b/tui/src/main.rsindex 56f01ddc3..1de0f08d2 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -526,7 +526,7 @@ async fn run(config: config::Config) -> io::Result<()> {let all = app.mouse && app.wants_motion();if all != mouse_all { execute!(term.backend_mut(), term_out::Mouse(if all { 2 } else { 1 }))?; mouse_all = all }app.flush_acks();- if refill && matches!(app.modal, Some(modal::Modal::Picker { .. })) { input::refill(&mut app) }+ if refill && matches!(app.modal, Some(modal::Modal::Picker { .. } | modal::Modal::NewHarness(_))) { input::refill(&mut app) }if std::mem::take(&mut app.redraw_all) { term.clear()?; need_draw = true; }if need_draw && last_draw.elapsed() >= frame_budget {// (The backend makes each frame's changes one synchronized update, and writes nothingdiff --git a/tui/src/modal.rs b/tui/src/modal.rsindex b4a906a92..47ef2f4d0 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -176,7 +176,7 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("restart", "Restart Harness", "⌥⇧E", "", "Harness"),("pause", "Pause Harness", "", "stop the engine, keep the conversation", "Harness"),("rename", "Rename Harness…", "", "", "Harness"),- ("take", "Take over this pane", "", "when another window has the keyboard", "Harness"),+ ("take", "Take Control", "", "reclaim all panes across every tab", "App"),("tab", "New Swarm", "⌥T", "", "Swarms"),("rename-tab", "Rename Swarm…", "⌥⇧R", "", "Swarms"),("close-tab", "Close Swarm", "⌥⇧W", "harnesses keep running", "Swarms"),@@ -208,7 +208,7 @@ fn span(text: impl Into<String>, style: Style) -> Span<'static> { Span::styled(tpub struct PopupLook { pub lines: String, pub style: String, pub border_style: String }pub fn agent_rows(app: &App, filter: Filter, machine: Option<&str>, project: Option<&str>) -> Vec<Row> {- let many = app.fleet.machines.iter().filter(|m| m.usable()).count() > 1;+ let many = app.fleet.visible_machines().filter(|m| m.usable()).count() > 1;// The project in each row when the harnesses work in more than one.let projects = { let mut p: Vec<&str> = app.fleet.agents.values().map(|a| a.project.as_str()).filter(|p| !p.is_empty()).collect(); p.sort(); p.dedup(); p.len() > 1 };let open: Vec<(String, String)> = app.panes.values().map(|p| (p.machine_id.clone(), p.agent_id.clone())).collect();@@ -282,7 +282,7 @@ pub fn agent_rows(app: &App, filter: Filter, machine: Option<&str>, project: Opt/// was said in them (never in the list as it opens): `not in Harness`, Enter resuming one as a/// harness; one open in another terminal or app is marked so, and not opened twice.pub fn external_rows(app: &App) -> Vec<Row> {- let many = app.fleet.machines.iter().filter(|m| m.usable()).count() > 1;+ let many = app.fleet.visible_machines().filter(|m| m.usable()).count() > 1;app.said.iter().filter_map(|s| s.external.as_ref()).map(|x| {let (mark, mark_color) = engine_mark(&x.engine);let folder = x.cwd.trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();@@ -388,7 +388,7 @@ pub fn project_rows(app: &App) -> Vec<Row> {if !matches!(app.fleet.state_of(a), State::Paused | State::Offline) { entry.1 += 1 }entry.2 = entry.2.max(a.recency());}- let many = app.fleet.machines.iter().filter(|m| m.usable()).count() > 1;+ let many = app.fleet.visible_machines().filter(|m| m.usable()).count() > 1;let mut rows: Vec<(u64, Row)> = groups.into_iter().map(|((machine, root), (all, live, recent))| {let name = root.rsplit('/').next().unwrap_or(&root).to_string();let home = app.homes.get(&machine).cloned().unwrap_or_else(|| std::env::var("HOME").unwrap_or_default());@@ -497,7 +497,7 @@ pub fn palette_rows(app: &App) -> Vec<Row> {pub const NEEDS_ARGS: &[&str] = &["select-window", "rename-window", "move-window", "select-pane", "resize-pane", "swap-pane", "select-layout", "send-keys", "command-prompt", "confirm-before", "display-message", "send-message", "rename-harness", "send-task", "broadcast"];pub fn machine_rows(app: &App) -> Vec<Row> {- app.fleet.machines.iter().map(|m| {+ app.fleet.visible_machines().map(|m| {// Its harnesses by what they do: the fleet's counts, for this machine.let here: Vec<State> = app.fleet.agents.values().filter(|a| a.machine_id == m.id && a.engine != "terminal").map(|a| app.fleet.state_of(a)).collect();let n = |s: State| here.iter().filter(|x| **x == s).count();@@ -514,7 +514,7 @@ pub fn machine_rows(app: &App) -> Vec<Row> {let counts = [(State::NeedsInput, "waiting"), (State::Failed, "failed"), (State::Done, "done"), (State::Working, "working"), (State::Ready, "idle")].iter().filter(|(s, _)| n(*s) > 0).map(|(s, w)| format!("{} {w}", n(*s))).collect::<Vec<_>>().join(" · ");let counts = format!("{rtt}{}", if counts.is_empty() { "no harnesses".into() } else { counts });- Row::new(m.id.clone(), m.name.clone()).extra(m.status.clone())+ Row::new(m.id.clone(), app.fleet.machine_name(&m.id)).extra(m.status.clone()).lead(vec![span(dot, fg(color)), span(" ", Style::default())]).detail(vec![span(word, fg(color))]).right(counts)@@ -527,9 +527,10 @@ pub fn layout_rows() -> Vec<Row> {pub fn new_machine_rows(app: &App, prefer: &str) -> Vec<Row> {- let mut rows: Vec<Row> = app.fleet.machines.iter().filter(|m| m.usable()).map(|m| {+ let prefer = app.fleet.launch_machine_id(prefer);+ let mut rows: Vec<Row> = app.fleet.visible_machines().filter(|m| m.usable()).map(|m| {let running = app.fleet.agents.values().filter(|a| a.machine_id == m.id && a.status == "active").count();- Row::new(m.id.clone(), m.name.clone())+ Row::new(m.id.clone(), app.fleet.machine_name(&m.id)).lead(vec![span(if m.id == prefer { "● " } else { "○ " }, fg(if m.id == prefer { theme::accent() } else { theme::ONLINE }))]).detail(vec![span(format!("{}{running} running", if m.local { "this computer · " } else { "" }), fg(theme::MUTED))])}).collect();diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rsindex e96077fca..da2cee2e9 100644--- a/tui/src/new_harness.rs+++ b/tui/src/new_harness.rs@@ -326,6 +326,7 @@ fn remember(form: &Form) {}pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {+ let machine = machine.map(|id| app.fleet.launch_machine_id(&id).to_string());if machine.as_ref().is_some_and(|id| !app.fleet.machines.iter().any(|m| m.id == *id && m.usable()))@@ -339,6 +340,7 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {|| (machine.is_none() && cwd.is_none() && app.new_harness_draft.is_some()){let mut form = app.new_harness_draft.take().unwrap();+ resolve_launch_machine(app, &mut form);refresh_form(app, &mut form);app.modal = Some(Modal::NewHarness(form));return;@@ -346,6 +348,7 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {let saved = defaults();let machine = machine.filter(|id| app.fleet.machines.iter().any(|m| m.id == *id && m.usable()))+ .or_else(|| app.fleet.registered_local_machine().filter(|m| m.usable()).map(|m| m.id.clone())).or_else(|| {app.fleet.machines@@ -502,10 +505,22 @@ pub fn refresh(app: &mut App) {let Some(Modal::NewHarness(mut form)) = app.modal.take() else {return;};+ resolve_launch_machine(app, &mut form);refresh_form(app, &mut form);sync_git(app, &mut form, false);app.modal = Some(Modal::NewHarness(form));}+fn resolve_launch_machine(app: &mut App, form: &mut Form) {+ // A pending receipt belongs to its original transport, even if the daemon has returned.+ if form.starting || form.attempt.is_some() { return }+ let machine = app.fleet.launch_machine_id(&form.draft.machine).to_string();+ if machine != form.draft.machine {+ let project = form.draft.project.clone();+ set_machine(app, form, &machine);+ set_project(form, project);+ sync_git(app, form, false);+ }+}fn agent_rows(app: &App, machine: &str) -> Vec<Row> {modal::new_what_rows(app.dsh.get(machine).map(Vec::as_slice).unwrap_or(&[]))}@@ -549,26 +564,28 @@ fn project_rows(app: &App, draft: &Draft) -> Vec<Row> {});let mut seen = std::collections::HashSet::new();for a in agents {- if !seen.insert((a.machine_id.clone(), a.cwd.clone())) {+ let machine = app.fleet.launch_machine_id(&a.machine_id);+ if !seen.insert((machine.to_string(), a.cwd.clone())) {continue;}let short = short_path(&a.cwd,app.homes- .get(&a.machine_id)+ .get(machine)+ .or_else(|| 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)),+ format!("at:{machine}\t{}", a.cwd),+ format!("{}:{short}", app.fleet.machine_name(machine)),).group("Recent projects");row.disabled = !app.fleet.machines.iter()- .any(|m| m.id == a.machine_id && m.usable());+ .any(|m| m.id == machine && m.usable());if row.disabled {row.label.push_str(" · offline");}@@ -1371,6 +1388,7 @@ pub fn start(app: &mut App) {crate::input::check_creation(app, id, attempt);return;}+ resolve_launch_machine(app, &mut form);let fail = if form.git_loading {Some("Checking the project…".into())} else if form.git["error"].is_string() {@@ -1563,6 +1581,64 @@ mod tests {app}+ #[tokio::test]+ async fn local_shell_entry_does_not_override_the_registered_launch_machine() {+ let mut app = app();+ let shell = crate::local::MACHINE;+ app.fleet.machines.insert(0, crate::fleet::Machine {+ id: shell.into(), name: "m0".into(), local: true,+ status: "running".into(), reach: crate::fleet::Reach::Ready,+ });+ for explicit in [None, Some(shell.into())] {+ 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");+ for rows in [modal::machine_rows(&app), modal::new_machine_rows(&app, shell)] {+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].id, "local");+ assert_eq!(rows[0].label, "studio");+ }+ }+ // Recent local-shell folders use that same machine and collapse duplicate paths.+ for machine in [shell, "local"] {+ let agent = crate::fleet::agent_from(machine, &json!({"id":"agent", "engine":"terminal", "project":{"cwd":"/home/dev/repo"}}), None);+ app.fleet.agents.insert(agent.key(), agent);+ }+ let Some(Modal::NewHarness(form)) = &app.modal else { panic!() };+ let rows = project_rows(&app, &form.draft);+ 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");+ }++ #[tokio::test]+ async fn daemon_return_redirects_an_idle_local_draft_but_keeps_a_pending_receipt() {+ for pending in [false, true] {+ let mut app = app();+ let shell = crate::local::MACHINE;+ app.fleet.machines.insert(0, crate::fleet::Machine {+ id: shell.into(), name: "m0".into(), local: true,+ status: "running".into(), reach: crate::fleet::Reach::Ready,+ });+ app.homes.insert(shell.into(), "/home/dev".into());+ app.fleet.machine_mut("local").unwrap().reach = crate::fleet::Reach::Offline;+ open(&mut app, Some(shell.into()), Some("/home/dev/repo".into()));+ let Some(Modal::NewHarness(form)) = &mut app.modal else { panic!() };+ if pending {+ form.attempt = Some(Creation { id: "original".into(), machine: shell.into(), session: app.session_id });+ }+ app.fleet.machine_mut("local").unwrap().reach = crate::fleet::Reach::Ready;+ app.fleet.machine_mut("local").unwrap().name = "office".into();+ 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");+ if pending { assert_eq!(form.attempt.as_ref().unwrap().machine, shell); }+ }+ }+#[tokio::test]async fn draft_survives_picker_escape_and_late_refresh() {let mut app = app();diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rsindex 54b7fdd0d..57e154f28 100644--- a/tui/src/new_harness/view.rs+++ b/tui/src/new_harness/view.rs@@ -170,21 +170,12 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {form.hits.push((Rect::new(r.x + 1, fy, r.width - 2, 1), *field));}- 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,+ &form.error,if form.error.is_empty() {muted} else {diff --git a/tui/src/pane.rs b/tui/src/pane.rsindex 9c5015981..1c44d1dfe 100644--- a/tui/src/pane.rs+++ b/tui/src/pane.rs@@ -96,6 +96,8 @@ pub struct Pane {/// select-pane -d: keys for this pane are dropped until select-pane -e.pub input_off: bool,pub opening: bool,+ /// A user requested app-wide control while this pane's passive open was in flight.+ pub takeover_pending: bool,pub read_only: bool,pub last_alive: Instant,pub dirty: bool,@@ -456,6 +458,7 @@ impl Pane {osc_title: String::new(),input_off: false,opening: false,+ takeover_pending: false,read_only: false,last_alive: Instant::now(),dirty: true,diff --git a/tui/src/preview.rs b/tui/src/preview.rsindex 21bacc572..e174b9013 100644--- a/tui/src/preview.rs+++ b/tui/src/preview.rs@@ -283,7 +283,7 @@ fn session(app: &App, id: &str) -> Vec<Line<'static>> {fn machine(app: &App, id: &str) -> Vec<Line<'static>> {let Some(m) = app.fleet.machine(id) else { return vec![] };- let mut out = vec![Line::from(vec![bold(m.name.clone()), dim(if m.local { " this computer" } else { "" })]), Line::raw("")];+ let mut out = vec![Line::from(vec![bold(app.fleet.machine_name(id)), dim(if m.local { " this computer" } else { "" })]), Line::raw("")];if let Some(rtt) = app.rtt.get(id) { out.push(kv("rtt", format!("{}ms", rtt.as_millis()))) }// Its agent accounts' rate limits (claude 5h 42% week 18%).for u in app.usage.get(id).into_iter().flatten() { out.push(kv("limits", u.line())) }diff --git a/tui/src/theme.rs b/tui/src/theme.rsindex 2da663b6c..54469bd91 100644--- a/tui/src/theme.rs+++ b/tui/src/theme.rs@@ -428,7 +428,7 @@ pub fn palette() -> (Color, Color, bool) {/// Surface colors derived from the terminal theme, with a stable fallback before OSC replies.#[derive(Clone, Copy, Debug)]pub struct PanePalette {- pub canvas: Color, pub surface: Color, pub inactive_surface: Color,+ pub surface: Color, pub inactive_surface: Color,pub foreground: Color, pub inactive_foreground: Color, pub muted: Color,pub active_foreground: Color,pub border: Color, pub active_border: Color,@@ -452,10 +452,12 @@ fn pane_palette_for(native: Option<(Color, Color)>) -> PanePalette {};let green = if light { Color::Rgb(58, 102, 48) } else { Color::Rgb(133, 181, 105) };let inactive_surface = if light { mix(bg, foreground, 8) } else { Color::Rgb(64, 64, 64) };+ // Panes sit directly on the native terminal background. Lift the focused fill+ // just enough to distinguish its edge while retaining the terminal's theme.+ let surface = mix(bg, foreground, if light { 4 } else { 10 });+ let surface = if surface == inactive_surface { mix(bg, foreground, if light { 2 } else { 6 }) } else { surface };PanePalette {- // Separate pane cards sit on a quiet backdrop, with clear space between outlines.- canvas: if light { mix(bg, foreground, 14) } else { Color::Rgb(32, 32, 32) },- surface: bg,+ surface,inactive_surface,foreground, inactive_foreground: mix(foreground, bg, 9),muted: mix(foreground, bg, 30),@@ -1279,9 +1281,8 @@ mod palette_tests {(Color::Rgb(247, 247, 247), Color::Rgb(26, 26, 26))] {let p = super::pane_palette_for(Some((bg, fg)));assert_ne!(p.surface, p.inactive_surface);- assert_ne!(p.inactive_surface, p.canvas);+ assert_ne!(p.surface, bg);assert_ne!(p.border, p.active_border);- assert_eq!(p.surface, bg);assert_eq!(p.foreground, fg);let luminance = |c: Color| { let Color::Rgb(r, g, b) = c else { panic!("RGB palette") };299 * r as i32 + 587 * g as i32 + 114 * b as i32 };@@ -1290,7 +1291,7 @@ mod palette_tests {assert!((luminance(p.status) - luminance(p.status_foreground)).abs() > 120_000);}let fallback = super::pane_palette_for(None);- assert_eq!(fallback.surface, Color::Rgb(28, 31, 36));+ assert_eq!(fallback.surface, Color::Rgb(47, 50, 55));assert_eq!(fallback.inactive_surface, Color::Rgb(64, 64, 64));}diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex fa72fd114..b219ef4a0 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -239,7 +239,7 @@ fn window(buf: &mut Buffer, app: &mut App, body: Rect) -> Option<Position> {let surfaces = app.options.pane_look();if surfaces {crate::term_out::clear_extras(body);- buf.set_style(body, Style::default().bg(theme::pane_palette().canvas));+ buf.set_style(body, Style::default().bg(Color::Reset));}let rects = app.rects.clone();let mut cursor = None;@@ -253,7 +253,7 @@ fn window(buf: &mut Buffer, app: &mut App, body: Rect) -> Option<Position> {let window = if active { (a.fg.or(w.fg), a.bg.or(w.bg)) } else { (w.fg, w.bg) };if surfaces {let f = crate::pane_frame::frame(*rect, app.window_area(app.tab()), app.pane_status(app.tab()));- // A single or zoomed pane keeps the same surface and surrounding canvas.+ // Single and zoomed panes also sit directly on the terminal background.buf.set_style(f.surface, Style::default().fg(window.0.unwrap_or(Color::Reset)).bg(window.1.unwrap_or(Color::Reset)));}// choose-tree's tree, over the pane.@@ -381,9 +381,10 @@ fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {let mut lines: Vec<Line> = Vec::new();if !compact { for w in WORDMARK { lines.push(Line::styled(w, fg(theme::accent()))) } lines.push(Line::raw("")) }else { lines.push(Line::styled("harness", bold(theme::accent()))) }- let local = app.fleet.machine(&app.fleet.local_id).map(|m| m.name.clone()).unwrap_or_default();- let up = app.fleet.machines.iter().filter(|m| m.usable()).count();- let sub = if app.fleet.machines.len() > 1 { format!("{local} · {up}/{} machines connected", app.fleet.machines.len()) } else { local };+ let local = app.fleet.local_machine_name();+ let up = app.fleet.visible_machines().filter(|m| m.usable()).count();+ let total = app.fleet.visible_machines().count();+ let sub = if total > 1 { format!("{local} · {up}/{total} machines connected") } else { local };lines.push(Line::styled(sub, fg(theme::MUTED)));lines.push(Line::raw(""));let centered = lines.len();@@ -397,7 +398,7 @@ fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {let hint = |c: &str| app.keymap.hint(c).unwrap_or_default();lines.push(Line::from(vec![Span::styled(hint("new-harness"), bold(theme::accent())), Span::styled(" starts a harness · ", fg(theme::MUTED)), Span::styled(hint("choose-tree -Zs"), bold(theme::accent())), Span::styled(" opens a paused one", fg(theme::MUTED))]));} else {- let many = app.fleet.machines.iter().filter(|m| m.usable()).count() > 1;+ let many = up > 1;for (index, row) in rows.iter().enumerate() {// A harness as its state says; a conversation Harness did not start as a paused one// would be (nothing running), its folder where the project goes.diff --git a/tui/tests/local-shells.py b/tui/tests/local-shells.pyindex dc0555aba..5eb37ecee 100644--- a/tui/tests/local-shells.py+++ b/tui/tests/local-shells.py@@ -186,7 +186,12 @@ try:wait(lambda: 'Mock Claude' in hn('list-harnesses', check=False).stdout, 'Harness daemon arrives', 15)send("printf 'WITH_DAEMON:%s:%s\\n' \"$$\" \"$HNE_PERSIST\"")wait(lambda: f'WITH_DAEMON:{pid}:remembered' in capture(), 'original local shell survives daemon arrival')- print('PASS daemon arrival preserves local shell', flush=True)+ 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')+ tm('send-keys', '-t', 'outer', 'Escape')+ print('PASS daemon arrival preserves local shell and uses the app machine name everywhere', flush=True)hn('kill-server', check=False)wait(lambda: not own_processes(), 'all test hn processes stop')@@ -217,6 +222,7 @@ try:wait(lambda: len(hn('list-windows', '-t', 'desk', '-F', '#{window_id}').stdout.splitlines()) == 2, 'local window after daemon loss')send('printf LOCAL_WINDOW', 'desk:1.0')wait(lambda: 'LOCAL_WINDOW' in capture('desk:1.0'), 'local window runs')+ assert hn('display-message', '-p', '-t', 'desk:1.0', '#{local_machine}|#{pane_machine}').stdout.strip() == 'mock-local|mock-local'os.kill(mock.pid, signal.SIGCONT)hn('send-keys', '-t', 'desk:0.0', 'RETURNED_DESK')wait(lambda: 'RETURNED_DESK' in capture('desk:0.0'), 'daemon stream reconnects', 25)diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex c2dffe2d6..8b2962c7b 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -484,6 +484,7 @@ wss.on('connection', (ws) => {case 'terminal_open': {if (reconnect) opens.push({ connection: connection.id, machine, agent: payload.agentId, takeover: payload.takeover, hung: connection.hang, at: Date.now() })if (reconnect && connection.hang) return // WS still answers pings; application requests do not.+ if (reconnect && payload.takeover === true) readOnly.delete(payload.agentId)const target = agents[machine].find((a) => a.id === payload.agentId)if (!target || target.status !== 'active') return send('terminal_error', { requestId: payload.requestId, code: 'TERMINAL_AGENT_NOT_FOUND' })const streamId = randomUUID()diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.pyindex 25f775eae..13d4f8fdf 100644--- a/tui/tests/new-harness.py+++ b/tui/tests/new-harness.py@@ -95,11 +95,21 @@ 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 placement():+ window, windows, panes = hn('display-message', '-p', '#{window_id} #{session_windows} #{window_panes}').split()+ return window, int(windows), int(panes)+def placed_in_current_window(before):+ window, windows, panes = before+ assert placement() == (window, windows, panes + 1), 'New Harness must add a pane in the current window'+ # Keep room for the next launch as this suite creates several harnesses in one window.+ hn('select-layout', 'tiled')def submit(count):# Git discovery is asynchronous. Wait for its answer before accepting the visible draft.time.sleep(.15)+ before = placement()keys('Enter')wait(lambda: create_count() == count and 'Options' not in screen(), 'created harness')+ placed_in_current_window(before)def raw(data):tmux('send-keys', '-H', '-t', 'test', *[f'{b:02x}' for b in data.encode()])@@ -187,8 +197,10 @@ try: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.+ before_terminal = placement()field('New Harness')wait(lambda: create_count() == before + 7 and 'Options' not in screen(), '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')), request@@ -214,6 +226,7 @@ try: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()+ before_recovery = placement()keys('Enter'); shows('Check status'); shows('Launch not confirmed')assert create_count() == count + 1request = state()['created'][-1]@@ -225,6 +238,7 @@ try:keys('Enter'); shows('Still starting your harness')assert create_count() == count + 1keys('Enter'); wait(lambda: 'Options' not in screen(), '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:]assert len(checks) == 2 and all(c['creationId'] == request['creationId'] for c in checks)diff --git a/tui/tests/pane-ui.py b/tui/tests/pane-ui.pyindex b673fd4e1..0911ad3ab 100644--- a/tui/tests/pane-ui.py+++ b/tui/tests/pane-ui.py@@ -176,7 +176,7 @@ try:started = Truewait(lambda: 'Fix flaky login test' in tmux('capture-pane', '-p', '-t', 'test'), 'demo panes')background('#000000')- wait(lambda: 'bg=#000000' in hn('show', '-gwv', 'window-active-style'), 'black terminal background')+ wait(lambda: 'bg=#181818' in hn('show', '-gwv', 'window-active-style'), 'focused pane lifted above the black terminal background')hn('select-layout', 'even-horizontal')panes = hn('list-panes', '-F', '#{pane_id}').splitlines()assert len(panes) == 3@@ -190,12 +190,12 @@ try:active_bg = hn('show', '-gwv', 'window-active-style').split('bg=')[1]inactive_bg = hn('show', '-gwv', 'window-style').split('bg=')[1]assert active_bg != inactive_bg- assert active_bg == '#000000' and inactive_bg == '#404040'+ assert active_bg == '#181818' and inactive_bg == '#404040'wait(lambda: not any(pane_outline(p) for p in (first, second, third)), 'pane backgrounds without outlines')wait(lambda: pane_background(first) == active_bg and pane_background(second) == inactive_bg, 'whole-pane focus contrast')- assert background_at(149, 0) == '#202020', 'dark backdrop surrounds the pane cards'+ assert background_at(149, 0) == 'default', 'outer margins use the native terminal background'wait(lambda: pane_edge_background(first, active_bg), 'focused background fills through the pane edges')- assert background_at(49, 20) == background_at(99, 20) == '#202020', 'dark gaps separate pane backgrounds'+ assert background_at(49, 20) == background_at(99, 20) == 'default', 'pane gaps use the native terminal background'assert pane_edge_background(second, inactive_bg)tab = value(hn('show', '-gwv', 'window-status-current-format'))label = value('#{window_index}:#{window_short_name}')@@ -319,8 +319,8 @@ try:assert '⎇ ' + value('#{pane_branch}') in branch_context, branch_contextassert 'git:(' not in branch_contextwait(lambda: not pane_outline(target) and background_at(1, 1) == active_bg- and background_at(0, 0) == background_at(149, 40) == '#202020',- 'zoomed pane keeps its focused surface inside the canvas')+ and background_at(0, 0) == background_at(149, 40) == 'default',+ 'zoomed pane sits directly on the terminal background')wait(lambda: background_at(0, 41) == normal_bg, 'status bar keeps its own color after transient completion notices')x, y, w = map(int, value('#{pane_left} #{pane_top} #{pane_width}', target).split())wait(lambda: tmux('capture-pane', '-p', '-t', 'test').splitlines()[y - 2][x:x + w].rstrip().endswith(branch_context), 'machine, project, branch and PR align to the right edge')@@ -431,9 +431,10 @@ try:layout_before_theme = value('#{window_layout}')before = len(api()['inputs'])background('#f7f7f7')- wait(lambda: hn('show', '-gwv', 'window-active-style') == 'fg=#1a1a1a,bg=#f7f7f7', 'light surface defaults')- wait(lambda: pane_background(first) == '#f7f7f7' and pane_background(second) == '#e5e5e5', 'light focus contrast')- wait(lambda: pane_edge_background(first, '#f7f7f7') and pane_title_color(first, foreground=False) == '#f7f7f7', 'light surface fills the focused pane through its padding')+ wait(lambda: hn('show', '-gwv', 'window-active-style') == 'fg=#1a1a1a,bg=#eeeeee', 'light surface defaults')+ wait(lambda: pane_background(first) == '#eeeeee' and pane_background(second) == '#e5e5e5', 'light focus contrast')+ wait(lambda: pane_edge_background(first, '#eeeeee') and pane_title_color(first, foreground=False) == '#eeeeee', 'light surface fills the focused pane through its padding')+ assert background_at(149, 0) == 'default', 'light theme also keeps the native terminal background'light_status = hn('show', '-gv', 'status-style')assert value('#{window_layout}') == layout_before_themesnapshot('panes-light')@@ -447,7 +448,7 @@ try:assert len(api()['inputs']) == before, 'terminal query replies reached an application'hn('set', '-gwu', 'window-style')assert hn('show', '-gwv', 'window-active-style').startswith('fg=#f5f5f5,')- wait(lambda: pane_background(first) == '#101010' and pane_background(second) == '#404040', 'dark focus contrast')+ wait(lambda: pane_background(first) == '#262626' and pane_background(second) == '#404040', 'dark focus contrast')print('PASS pane UI: live light/dark themes, reported defaults and custom style preservation', flush=True)hn('send-keys', '-t', first, '-l', '\x1b[H\x1b[31;44mHN_COLOR\x1b[0m')@@ -464,9 +465,9 @@ try:single = hn('new-window', '-n', 'single', '-P', '-F', '#{pane_id}', '/bin/sh')wait(lambda: value('#{pane_id}') == single and value('#{window_panes}') == '1', 'single-pane window')- wait(lambda: not pane_outline(single) and background_at(1, 1) == '#101010'- and background_at(0, 0) == background_at(149, 40) == '#202020',- 'single pane keeps its focused surface inside the canvas')+ wait(lambda: not pane_outline(single) and background_at(1, 1) == '#262626'+ and background_at(0, 0) == background_at(149, 40) == 'default',+ 'single pane sits directly on the terminal background')snapshot('panes-single')hn('kill-window')wait(lambda: value('#{window_id}') == current, 'return from single-pane window')diff --git a/tui/tests/reconnect.py b/tui/tests/reconnect.pyindex e67552202..3c5a60747 100644--- a/tui/tests/reconnect.py+++ b/tui/tests/reconnect.py@@ -153,6 +153,40 @@ try:echo(codex, 'RECOVERED_SOCKET')print('PASS: dropped socket recovery', flush=True)+ # One deliberate claim reclaims every tab, including the hidden remote pane.+ def watched(agent):+ return hn('display-message', '-p', '-t', pane_for(agent), '#{pane_watched}') == '1'++ def displace_all():+ start = len(api()['opens'])+ for agent in panes:+ fault('watch', agent=agent)+ fault('close', agent=agent, takenBy='another app')+ wait(lambda: all(watched(a) for a in panes), 'every pane is watching')+ assert all(o['takeover'] is False for o in api()['opens'][start:]), 'ownership notifications reclaimed control'++ displace_all()+ focus = hn('display-message', '-p', '#{window_id}:#{pane_id}')+ layouts = hn('list-windows', '-F', '#{window_id}:#{window_layout}')+ before = api()+ hn('take-control')+ wait(lambda: len(api()['opens']) == len(before['opens']) + len(panes) and all(not watched(a) for a in panes), 'one command reclaims all local and remote tabs')+ claims = api()['opens'][len(before['opens']):]+ assert len(claims) == len(panes) and all(o['takeover'] is True for o in claims), claims+ assert {o['agent'] for o in claims} == set(panes)+ assert hn('display-message', '-p', '#{window_id}:#{pane_id}') == focus+ assert hn('list-windows', '-F', '#{window_id}:#{window_layout}') == layouts+ assert api()['inputs'] == before['inputs'], 'take-control typed into a terminal'+ hn('take')+ assert len(api()['opens']) == len(before['opens']) + len(panes), 'repeat claim reopened controlled panes'+ displace_all()+ before = api()+ hn('send-keys', '-t', pane_for(claude), '-l', 'CLAIMED_ALL_TABS')+ wait(lambda: all(not watched(a) for a in panes), 'typing in a watcher reclaims every tab')+ wait(lambda: 'CLAIMED_ALL_TABS' in hn('capture-pane', '-p', '-t', pane_for(claude)), 'claim preserves typed input')+ assert {i['agent'] for i in api()['inputs'][len(before['inputs']):]} == {claude}, 'typed input leaked to another pane'+ print('PASS: app-wide control, hidden local/remote tabs, stable focus, idempotence and isolated input', flush=True)+# Genuine terminal/process closure remains a card; it must not restart the program.before_count = len(api()['opens'])fault('close', machine=LOCAL, agent=claude, reason='process exited')