A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(gui): show worktrees and the active pane in the Agents panel
RoversX58a35abb94a9
diff --git a/Cargo.lock b/Cargo.lockindex 7889b28f..9c1416c4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10611,6 +10611,7 @@ dependencies = ["frecency","futures","hdrhistogram",+ "hostname","image","k9","lazy_static",diff --git a/mux/src/foreground_program.rs b/mux/src/foreground_program.rsindex f3ae4d6c..a04ccd1b 100644--- a/mux/src/foreground_program.rs+++ b/mux/src/foreground_program.rs@@ -375,7 +375,9 @@ fn choose(}}-fn is_remote_session_client(program: &ForegroundProgram) -> bool {+/// Whether `program` is a client whose terminal is on another machine:+/// `ssh`, `mosh` and the like.+pub fn is_remote_session_client(program: &ForegroundProgram) -> bool {let name = program.runs.as_deref().unwrap_or(&program.executable);REMOTE_SESSION_CLIENTS.contains(&name)}diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex b6e0b49a..fe4783e0 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -70,6 +70,7 @@ thinkterm-i18n.workspace = truefrecency.workspace = truefutures.workspace = truehdrhistogram.workspace = true+hostname.workspace = truethinkterm-file-index.workspace = trueimage.workspace = truelazy_static.workspace = truediff --git a/wezterm-gui/src/agent_status/mod.rs b/wezterm-gui/src/agent_status/mod.rsindex 8737b4a0..e4d83313 100644--- a/wezterm-gui/src/agent_status/mod.rs+++ b/wezterm-gui/src/agent_status/mod.rs@@ -27,6 +27,8 @@ use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Mutex;use std::time::{Duration, Instant};+mod worktree;+/// Clickable controls in the Agents panel; carried by/// `UIItemType::RightSidebarAgent`.#[derive(Clone, Debug, PartialEq, Eq)]@@ -75,6 +77,9 @@ pub(crate) struct AgentPaneStatus {/// `workspace_threads::thread_place_and_machine_for_workspace` keys it;/// empty for this device. Resolved with `place`, once per snapshot.pub machine: String,+ /// The git worktree its directory is in, when that is on this device.+ /// Resolved with `place`, once per snapshot.+ pub worktree: Option<worktree::Worktree>,/// What the program said about itself with OSC 7501, when it did.pub report: Option<ProgramReport>,/// Unix seconds when `state` last changed, on the detecting host's@@ -194,11 +199,34 @@ pub(crate) fn agent_panes() -> std::sync::Arc<Vec<AgentPaneStatus>> {Some((window_id, workspace)) => (Some(*window_id), workspace.clone()),None => (None, String::new()),};- let (place, machine) = if workspace.is_empty() {- (String::new(), String::new())+ let thread = if workspace.is_empty() {+ None} else {crate::workspace_threads::thread_place_and_machine_for_workspace(&workspace)- .unwrap_or_else(|| (workspace.clone(), String::new()))+ };+ // Only this device's own files can say which worktree it is in:+ // for a thread of this device, with no ssh or mosh in front, in+ // a shell that does not report another machine.+ let here = thread+ .as_ref()+ .is_some_and(|(_, machine)| machine.is_empty())+ && !pane.foreground_program().is_some_and(|program| {+ mux::foreground_program::is_remote_session_client(&program)+ })+ && pane+ .copy_user_vars()+ .get("WEZTERM_HOST")+ .is_none_or(|host| worktree::names_this_machine(host));+ let worktree = if here {+ pane.get_current_working_dir(mux::pane::CachePolicy::AllowStale)+ .and_then(|url| worktree::worktree_of(&url))+ } else {+ None+ };+ let (place, machine) = match thread {+ Some(thread) => thread,+ None if workspace.is_empty() => (String::new(), String::new()),+ None => (workspace.clone(), String::new()),};let raw_title = pane.get_title();let title =@@ -218,6 +246,7 @@ pub(crate) fn agent_panes() -> std::sync::Arc<Vec<AgentPaneStatus>> {place,workspace,machine,+ worktree,report: status.report,since_unix: status.since_unix,})@@ -762,6 +791,7 @@ mod tests {place: place.to_string(),workspace: String::new(),machine: String::new(),+ worktree: None,report: None,since_unix: 0,}diff --git a/wezterm-gui/src/agent_status/worktree.rs b/wezterm-gui/src/agent_status/worktree.rsnew file mode 100644index 00000000..face1ec2--- /dev/null+++ b/wezterm-gui/src/agent_status/worktree.rs@@ -0,0 +1,446 @@+//! The git worktree an agent's pane is in, for the Agents panel: the folder+//! it is checked out in and the branch there. Read from the files git keeps+//! rather than by running git, on a thread of its own -- a directory on a+//! stalled network mount, or a file not yet downloaded, blocks whoever+//! reads it -- and kept per directory, so the panel only ever looks it up.++use std::collections::HashMap;+use std::io::Read;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::{LazyLock, Mutex};+use std::time::{Duration, Instant};++#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct Worktree {+ /// The folder it is checked out in, by name.+ pub folder: String,+ /// The branch checked out, or the commit when none is.+ pub branch: Option<String>,+}++impl Worktree {+ /// The line the panel shows: "folder · branch".+ pub fn label(&self) -> String {+ match &self.branch {+ Some(branch) => format!("{} \u{b7} {}", self.folder, branch),+ None => self.folder.clone(),+ }+ }+}++/// How long an answer stands before it is looked up again; a branch+/// switched meanwhile shows after about this.+const KEEP_FOR: Duration = Duration::from_secs(5);+/// How many directories are remembered, the one asked about least recently+/// going first: agents sit in far fewer.+const MAX_DIRECTORIES: usize = 64;+/// Lookups at once. One stuck on a dead mount keeps its slot -- and its+/// directory the answer it had -- for good, so a few such directories+/// cannot pile up threads.+const MAX_LOOKUPS: usize = 4;+/// How long this machine's names are reused: a Mac's can follow the+/// network it is on.+const NAMES_KEEP_FOR: Duration = Duration::from_secs(30);++struct Known {+ worktree: Option<Worktree>,+ /// When the answer was read, once it has been.+ read_at: Option<Instant>,+ /// When the panel last asked, which decides what is forgotten first.+ asked_at: Instant,+ looking: bool,+ /// Asked while every lookup slot was taken. It goes when one frees: a+ /// panel with nothing moving does not ask again.+ waiting: bool,+}++static KNOWN: LazyLock<Mutex<HashMap<PathBuf, Known>>> = LazyLock::new(Default::default);+static LOOKUPS: AtomicUsize = AtomicUsize::new(0);++/// The worktree a pane whose directory is `url` is in, as last looked up:+/// `None` until it has been, or when the directory is on another machine+/// or in no worktree. A stale answer has a fresh lookup started.+pub(crate) fn worktree_of(url: &url::Url) -> Option<Worktree> {+ let dir = local_dir(url, &this_machine_names())?;+ let now = Instant::now();+ let mut known = KNOWN.lock().ok()?;+ let new = !known.contains_key(&dir);+ let entry = known.entry(dir.clone()).or_insert_with(|| Known {+ worktree: None,+ read_at: None,+ asked_at: now,+ looking: false,+ waiting: false,+ });+ entry.asked_at = now;+ let stale = entry+ .read_at+ .is_none_or(|at| now.duration_since(at) >= KEEP_FOR);+ let needs_lookup = stale && !entry.looking;+ let worktree = entry.worktree.clone();+ if needs_lookup {+ if LOOKUPS.load(Ordering::Relaxed) < MAX_LOOKUPS {+ start_lookup(&mut known, &dir);+ } else if let Some(entry) = known.get_mut(&dir) {+ entry.waiting = true;+ }+ }+ if new {+ forget_least_asked(&mut known);+ }+ worktree+}++/// Look `dir` up on a thread of its own, in a slot. The slots are counted+/// with the map's lock held, as here.+fn start_lookup(known: &mut HashMap<PathBuf, Known>, dir: &Path) {+ let Some(entry) = known.get_mut(dir) else {+ return;+ };+ entry.looking = true;+ entry.waiting = false;+ LOOKUPS.fetch_add(1, Ordering::Relaxed);+ let spawned = std::thread::Builder::new()+ .name("worktree lookup".to_string())+ .spawn({+ let dir = dir.to_path_buf();+ move || look_up(dir)+ });+ if spawned.is_err() {+ entry.looking = false;+ LOOKUPS.fetch_sub(1, Ordering::Relaxed);+ }+}++fn look_up(dir: PathBuf) {+ let worktree = read_worktree(&dir);+ let changed = match KNOWN.lock() {+ Ok(mut known) => {+ // A directory being looked up is never forgotten.+ let changed = match known.get_mut(&dir) {+ Some(entry) => {+ let changed = entry.worktree != worktree;+ entry.worktree = worktree;+ // Stamped once read: a read that took longer than+ // KEEP_FOR was otherwise stale on arrival, and looked up+ // again.+ entry.read_at = Some(Instant::now());+ entry.looking = false;+ changed+ }+ None => false,+ };+ LOOKUPS.fetch_sub(1, Ordering::Relaxed);+ if let Some(next) = next_waiting(&known) {+ start_lookup(&mut known, &next);+ }+ changed+ }+ Err(_) => {+ LOOKUPS.fetch_sub(1, Ordering::Relaxed);+ false+ }+ };+ if changed {+ promise::spawn::spawn_into_main_thread(async {+ // There, not here: a snapshot the GUI was building meanwhile+ // would be stored after this, with the old answer in it.+ super::invalidate_agent_pane_cache();+ if let Some(front_end) = crate::frontend::try_front_end() {+ front_end.invalidate_all_windows();+ }+ })+ .detach();+ }+}++/// The directory a freed slot goes to: of those that found none free, the+/// one asked about last.+fn next_waiting(known: &HashMap<PathBuf, Known>) -> Option<PathBuf> {+ known+ .iter()+ .filter(|(_, entry)| entry.waiting && !entry.looking)+ .max_by_key(|(_, entry)| entry.asked_at)+ .map(|(dir, _)| dir.clone())+}++/// Keep to the bound: the directory asked about least recently goes, never+/// one being looked up.+fn forget_least_asked(known: &mut HashMap<PathBuf, Known>) {+ while known.len() > MAX_DIRECTORIES {+ let least = known+ .iter()+ .filter(|(_, entry)| !entry.looking)+ .min_by_key(|(_, entry)| entry.asked_at)+ .map(|(dir, _)| dir.clone());+ match least {+ Some(dir) => known.remove(&dir),+ None => break,+ };+ }+}++/// This machine's names as a shell may report them: its host name, and on+/// Windows the computer name PowerShell's `$env:COMPUTERNAME` gives, which+/// is cut to 15 characters.+fn this_machine_names() -> Vec<String> {+ static NAMES: Mutex<Option<(Instant, Vec<String>)>> = Mutex::new(None);+ let now = Instant::now();+ let mut cached = match NAMES.lock() {+ Ok(cached) => cached,+ Err(_) => return read_machine_names(),+ };+ if let Some((at, names)) = cached.as_ref() {+ if now.duration_since(*at) < NAMES_KEEP_FOR {+ return names.clone();+ }+ }+ let names = read_machine_names();+ *cached = Some((now, names.clone()));+ names+}++fn read_machine_names() -> Vec<String> {+ let mut names: Vec<String> = hostname::get()+ .ok()+ .map(|name| name.to_string_lossy().into_owned())+ .into_iter()+ .collect();+ if cfg!(windows) {+ names.extend(std::env::var("COMPUTERNAME").ok());+ }+ names.retain(|name| !name.is_empty());+ names+}++/// Whether a shell's report of the machine it runs on -- a `file:` URL's+/// host, the `WEZTERM_HOST` user var -- names this one.+pub(crate) fn names_this_machine(host: &str) -> bool {+ is_this_machine(host, &this_machine_names())+}++/// Whether `host` is this machine: no name, `localhost`, or one of+/// `names`. A shell reports its directory with the name of the machine it+/// runs on, which after an `ssh` is the other one.+fn is_this_machine(host: &str, names: &[String]) -> bool {+ host.is_empty()+ || host.eq_ignore_ascii_case("localhost")+ || names.iter().any(|name| same_machine(host, name))+}++/// A name and the same name with a domain (`myhost`, `myhost.local`) are+/// one machine; the same first part under two domains is two.+fn same_machine(a: &str, b: &str) -> bool {+ if a.eq_ignore_ascii_case(b) {+ return true;+ }+ match (a.split_once('.'), b.split_once('.')) {+ (Some((short, _)), None) => short.eq_ignore_ascii_case(b),+ (None, Some((short, _))) => a.eq_ignore_ascii_case(short),+ _ => false,+ }+}++/// The path a pane's directory `url` names on this machine.+fn local_dir(url: &url::Url, names: &[String]) -> Option<PathBuf> {+ if url.scheme() != "file" || !is_this_machine(url.host_str().unwrap_or(""), names) {+ return None;+ }+ let path = percent_encoding::percent_decode_str(url.path())+ .decode_utf8()+ .ok()?;+ // `/C:/Users/...` on Windows.+ let path = match path.strip_prefix('/') {+ Some(rest) if cfg!(windows) && rest.as_bytes().get(1) == Some(&b':') => rest,+ _ => &path,+ };+ (!path.is_empty()).then(|| PathBuf::from(path))+}++/// The worktree `dir` is in: the nearest folder at or above it with a+/// `.git` -- a directory in a repository's own checkout, a file naming the+/// git directory in a linked worktree or a submodule.+fn read_worktree(dir: &Path) -> Option<Worktree> {+ for folder in dir.ancestors() {+ let dot_git = folder.join(".git");+ let git_dir = if dot_git.is_dir() {+ dot_git+ } else if dot_git.is_file() {+ let text = read_small_file(&dot_git)?;+ folder.join(text.lines().next()?.strip_prefix("gitdir:")?.trim())+ } else {+ continue;+ };+ let branch = read_small_file(&git_dir.join("HEAD")).and_then(|head| branch_of_head(&head));+ return Some(Worktree {+ folder: folder.file_name()?.to_string_lossy().into_owned(),+ branch,+ });+ }+ None+}++/// The text of a file git keeps: only a plain one -- a FIFO would block the+/// read, a device would not end it -- and no longer than git writes there.+fn read_small_file(path: &Path) -> Option<String> {+ if !std::fs::metadata(path).ok()?.is_file() {+ return None;+ }+ let mut text = String::new();+ std::fs::File::open(path)+ .ok()?+ .take(4096)+ .read_to_string(&mut text)+ .ok()?;+ Some(text)+}++/// The branch a `HEAD` file names, or the start of the commit it holds when+/// detached. A reftable repository keeps its real HEAD elsewhere and leaves+/// `refs/heads/.invalid` in the file, which is no branch.+fn branch_of_head(head: &str) -> Option<String> {+ let head = head.trim();+ match head.strip_prefix("ref: ") {+ Some(reference) => {+ let branch = reference.strip_prefix("refs/heads/").unwrap_or(reference);+ (branch != ".invalid").then(|| branch.to_string())+ }+ None => (head.len() >= 7 && head.chars().all(|c| c.is_ascii_hexdigit()))+ .then(|| head[..7].to_string()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_head_names_its_branch_or_its_commit() {+ assert_eq!(+ branch_of_head("ref: refs/heads/main\n").as_deref(),+ Some("main")+ );+ assert_eq!(+ branch_of_head("ref: refs/heads/feature/login\r\n").as_deref(),+ Some("feature/login")+ );+ assert_eq!(+ branch_of_head("a1b2c3d4e5f60718\n").as_deref(),+ Some("a1b2c3d")+ );+ assert_eq!(branch_of_head("ref: refs/heads/.invalid\n"), None);+ assert_eq!(branch_of_head("not a head"), None);+ }++ #[test]+ fn only_this_machine_s_directories_are_read() {+ let url = |text: &str| url::Url::parse(text).unwrap();+ let here = ["myhost.local".to_string()];+ assert_eq!(+ local_dir(&url("file:///home/user/project"), &here),+ Some(PathBuf::from("/home/user/project"))+ );+ assert!(local_dir(&url("file://localhost/home/user/project"), &here).is_some());+ assert!(local_dir(&url("file://MYHOST/home/user/project"), &here).is_some());+ assert_eq!(+ local_dir(&url("file://myhost.local/home/user/a%20b"), &here),+ Some(PathBuf::from("/home/user/a b"))+ );+ // After `ssh server`, the shell there names its own machine.+ assert_eq!(+ local_dir(&url("file://server/home/user/project"), &here),+ None+ );+ assert_eq!(local_dir(&url("https://example.com/x"), &here), None);+ }++ #[test]+ fn the_same_first_name_under_two_domains_is_two_machines() {+ let here = ["myhost.local.example".to_string()];+ assert!(is_this_machine("myhost.local.example", &here));+ assert!(is_this_machine("MYHOST", &here));+ assert!(!is_this_machine("myhost.remote.example", &here));+ // PowerShell gives the computer name, the host name's first 15+ // characters.+ let windows = [+ "myhost-workstation".to_string(),+ "MYHOST-WORKSTAT".to_string(),+ ];+ assert!(is_this_machine("MYHOST-WORKSTAT", &windows));+ assert!(!is_this_machine("server", &windows));+ }++ fn entry(asked_at: Instant, looking: bool, waiting: bool) -> Known {+ Known {+ worktree: None,+ read_at: None,+ asked_at,+ looking,+ waiting,+ }+ }++ #[test]+ fn a_freed_slot_goes_to_the_directory_asked_about_last() {+ let start = Instant::now();+ let at = |ms: u64| start + Duration::from_millis(ms);+ let mut known = HashMap::new();+ known.insert(PathBuf::from("/early"), entry(at(1), false, true));+ known.insert(PathBuf::from("/late"), entry(at(3), false, true));+ known.insert(PathBuf::from("/busy"), entry(at(4), true, false));+ known.insert(PathBuf::from("/done"), entry(at(5), false, false));+ assert_eq!(next_waiting(&known), Some(PathBuf::from("/late")));+ known.clear();+ assert_eq!(next_waiting(&known), None);+ }++ #[test]+ fn the_directory_asked_about_least_recently_goes_first() {+ let start = Instant::now();+ let mut known: HashMap<PathBuf, Known> = (0..=MAX_DIRECTORIES)+ .map(|at| {+ let asked_at = start + Duration::from_millis(at as u64 + 1);+ (+ PathBuf::from(format!("/dir/{at}")),+ entry(asked_at, false, false),+ )+ })+ .collect();+ // The oldest of all, but still being looked up.+ known.insert(PathBuf::from("/stuck"), entry(start, true, false));+ forget_least_asked(&mut known);+ assert_eq!(known.len(), MAX_DIRECTORIES);+ assert!(known.contains_key(Path::new("/stuck")));+ assert!(!known.contains_key(Path::new("/dir/0")));+ assert!(!known.contains_key(Path::new("/dir/1")));+ assert!(known.contains_key(Path::new("/dir/2")));+ }++ #[test]+ fn a_checkout_and_a_linked_worktree_each_name_their_own_folder() {+ let root = tempfile::tempdir().unwrap();+ let main = root.path().join("project");+ std::fs::create_dir_all(main.join(".git/worktrees/project-fix")).unwrap();+ std::fs::write(main.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();+ std::fs::write(+ main.join(".git/worktrees/project-fix/HEAD"),+ "ref: refs/heads/fix\n",+ )+ .unwrap();+ let linked = root.path().join("project-fix");+ std::fs::create_dir_all(linked.join("src")).unwrap();+ // As `git worktree add --relative-paths` writes it.+ std::fs::write(+ linked.join(".git"),+ "gitdir: ../project/.git/worktrees/project-fix\r\n",+ )+ .unwrap();+ std::fs::create_dir_all(main.join("src/deep")).unwrap();++ let checkout = read_worktree(&main.join("src/deep")).unwrap();+ assert_eq!(checkout.label(), "project \u{b7} main");+ let worktree = read_worktree(&linked.join("src")).unwrap();+ assert_eq!(worktree.label(), "project-fix \u{b7} fix");+ }+}diff --git a/wezterm-gui/src/termwindow/ui/agent_panel.rs b/wezterm-gui/src/termwindow/ui/agent_panel.rsindex 3a2e63aa..54adb08d 100644--- a/wezterm-gui/src/termwindow/ui/agent_panel.rs+++ b/wezterm-gui/src/termwindow/ui/agent_panel.rs@@ -247,6 +247,11 @@ impl TermWindow {// Between rows of a group: plain enough to stay out of the way, but// a shade firmer than the separator token, which vanished here.let divider = muted_fg.mul_alpha(0.22);+ // The agent in the pane this window is on lies on a faint tint of+ // the accent, so the list shows where you are; a hover still shows+ // through it.+ let active_pane_id = self.get_active_pane_no_overlay().map(|pane| pane.pane_id());+ let active_tint = chrome.accent.mul_alpha(0.14);// A working description shimmers from the quieter grey up to white// (black on a light theme): from the brighter grey the light that// passed was too close to the text to see.@@ -470,6 +475,21 @@ impl TermWindow {).context("agent row hover")?;}+ if Some(agent.pane_id) == active_pane_id {+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(+ content_x as f32,+ band.visible_y as f32,+ content_width as f32,+ band.visible_height as f32,+ ),+ active_tint,+ self.ui_f32(SIDEBAR_ROW_RADIUS) + 10.0,+ )+ .context("active agent row")?;+ }let in_this_window = agent.window_id == Some(self.mux_window_id);self.ui_items.push(UIItem {x: content_x,@@ -609,6 +629,34 @@ impl TermWindow {)?;}line_y += cell_height + line_gap;+ // Which worktree: threads are named after tasks, and several+ // can share a name while their checkouts differ.+ if let Some(worktree) = agent.worktree.as_ref().filter(|_| layout.worktree) {+ if visible(line_y, cell_height) {+ let branch_size = (cell_height * 4 / 5).max(1);+ let branch_y = line_y + (cell_height - branch_size) / 2;+ self.paint_sidebar_icon(+ layers,+ SvgIcon::GitBranch,+ text_x,+ branch_y,+ branch_size,+ muted_fg,+ )?;+ let label_x = text_x + branch_size + metrics.icon_gap / 2;+ self.paint_agent_text(+ layers,+ ui_font,+ ui_metrics,+ &worktree.label(),+ label_x,+ line_y,+ text_right.saturating_sub(label_x),+ muted_fg,+ )?;+ }+ line_y += cell_height + line_gap;+ }let Some(report) = agent.report.as_ref() else {continue;@@ -1775,6 +1823,8 @@ struct AgentRowLayout {height: usize,/// The description, with the waiting reason in front of it.message: bool,+ /// The git worktree it is in, under the place.+ worktree: bool,progress: Option<u8>,/// The sub-tasks the folded line counts; none when they are not shown.subtask_count: usize,@@ -1793,10 +1843,13 @@ impl AgentRowLayout {line: usize,bar: usize,) -> Self {+ let worktree = agent.worktree.is_some();+ let base_height = base_height + if worktree { line } else { 0 };let Some(report) = agent.report.as_ref() else {return Self {height: base_height,message: false,+ worktree,progress: None,subtask_count: 0,subtasks: 0,@@ -1821,6 +1874,7 @@ impl AgentRowLayout {Self {height,message,+ worktree,progress,subtask_count,subtasks,@@ -2244,6 +2298,7 @@ mod tests {place: String::new(),workspace: String::new(),machine: String::new(),+ worktree: None,report: Some(ProgramReport {state: ProgramReportState::Working,kind: None,@@ -2294,6 +2349,7 @@ mod tests {place: place.to_string(),workspace: String::new(),machine: String::new(),+ worktree: None,report: None,since_unix,}