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
procinfo + mux: agent-aware foreground selection on Windows
RoversX2bb9754da766
diff --git a/mux/src/agent_status/identify.rs b/mux/src/agent_status/identify.rsindex 416e2e6a..b1963603 100644--- a/mux/src/agent_status/identify.rs+++ b/mux/src/agent_status/identify.rs@@ -53,23 +53,32 @@ fn probe(pane: &dyn Pane) -> CachedIdent {} else {CachePolicy::FetchImmediate};- let leader_path = pane- .get_foreground_process_name(policy)- .map(normalize_executable_path);- let resolved = CachedIdent {- at: now,- agent: leader_path.as_deref().and_then(|path| {+ // Windows has no tty foreground group: identification walks the+ // pane's process tree instead (falling back to the youngest-console+ // heuristic when the tree names no agent).+ #[cfg(windows)]+ let (leader_path, agent) = super::windows_select::probe_pane(pane, policy);+ #[cfg(not(windows))]+ let (leader_path, agent) = {+ let leader_path = pane+ .get_foreground_process_name(policy)+ .map(normalize_executable_path);+ let agent = leader_path.as_deref().and_then(|path| {// argv is fetched only if the leader turns out to be a generic// interpreter, and always AllowStale: the name probe one step// up just refreshed the leader cache, so this reuses that same// pid. Re-probing here could race a foreground change and pair- // this argv with the other probe's path — and on Windows a- // FetchImmediate would repeat a full process-table walk.+ // this argv with the other probe's path.let mut argv = || pane.get_foreground_process_argv(CachePolicy::AllowStale);super::proc_match::identify(path, &mut argv, &|name| {super::engine::manifest_id_for_alias(name)})- }),+ });+ (leader_path, agent)+ };+ let resolved = CachedIdent {+ at: now,+ agent,leader_path,};@@ -127,7 +136,7 @@ pub fn forget_pane(pane_id: crate::pane::PaneId) {/// keeps both identification and the contract's leader-path equality/// working across an in-place update. macOS resolves via `proc_pidpath`,/// which never decorates the path, so this is a no-op there.-fn normalize_executable_path(path: String) -> String {+pub(crate) fn normalize_executable_path(path: String) -> String {match path.strip_suffix(" (deleted)") {Some(stripped) => stripped.to_string(),None => path,diff --git a/mux/src/agent_status/windows_select.rs b/mux/src/agent_status/windows_select.rsnew file mode 100644index 00000000..953db4ce--- /dev/null+++ b/mux/src/agent_status/windows_select.rs@@ -0,0 +1,243 @@+//! Agent-aware foreground selection for Windows, ported from herdr's+//! design: no tty foreground group exists there, so walk the pane's+//! process tree in a shared Toolhelp32 snapshot, identify every+//! candidate, and let the topmost-ancestor agent win — claude beats the+//! node MCP child it spawned. The youngest-console heuristic behind+//! `get_foreground_process_name` keeps serving every non-agent consumer+//! (tab titles, close prompts) untouched.+//!+//! The selection core is pure and host-tested; only the fact-gathering+//! glue is `cfg(windows)`. Deferred, deliberately: git-bash re-parents+//! processes out of the shell's subtree (herdr tags panes with an env+//! marker and scans machine-wide), and PEB-environment identity hints.++use procinfo::ProcessTableEntry;++/// Pick the agent pid for a pane rooted at `root`. `identify` is called+/// once per tree member (root included) with its table entry and returns+/// the manifest id when that process is an agent; the callback decides+/// how much it wants to pay per process (name first, argv on demand).+///+/// Selection: the candidate that is an ancestor of every other candidate+/// wins. Candidates that form no single chain mean the tree is ambiguous+/// — return `None` and let the caller fall back, matching herdr.+#[cfg_attr(not(windows), allow(dead_code))]+pub(crate) fn select_agent(+ entries: &[ProcessTableEntry],+ root: u32,+ identify: &mut dyn FnMut(&ProcessTableEntry) -> Option<String>,+) -> Option<(u32, String)> {+ let mut children: std::collections::HashMap<u32, Vec<&ProcessTableEntry>> =+ std::collections::HashMap::new();+ let mut by_pid: std::collections::HashMap<u32, &ProcessTableEntry> =+ std::collections::HashMap::new();+ for entry in entries {+ children.entry(entry.ppid).or_default().push(entry);+ by_pid.insert(entry.pid, entry);+ }++ // The tree under (and including) the root. Pid reuse can fabricate+ // parent links that loop; the visited set bounds the walk.+ let mut members: Vec<&ProcessTableEntry> = Vec::new();+ let mut visited: std::collections::HashSet<u32> = std::collections::HashSet::new();+ let mut queue: Vec<u32> = vec![root];+ while let Some(pid) = queue.pop() {+ if !visited.insert(pid) {+ continue;+ }+ if let Some(entry) = by_pid.get(&pid) {+ members.push(entry);+ }+ if let Some(kids) = children.get(&pid) {+ queue.extend(kids.iter().map(|kid| kid.pid));+ }+ }++ let mut candidates: Vec<(&ProcessTableEntry, String)> = Vec::new();+ for entry in &members {+ if let Some(agent) = identify(entry) {+ candidates.push((entry, agent));+ }+ }+ if candidates.is_empty() {+ return None;+ }++ // Ancestor-of-all wins. Ancestry is checked inside the member set+ // only, again visit-bounded against pid-reuse loops.+ let is_ancestor = |ancestor: u32, mut pid: u32| -> bool {+ let mut seen = std::collections::HashSet::new();+ while pid != ancestor {+ if !seen.insert(pid) {+ return false;+ }+ match by_pid.get(&pid) {+ Some(entry) if visited.contains(&entry.ppid) && entry.ppid != entry.pid => {+ pid = entry.ppid;+ }+ _ => return false,+ }+ }+ true+ };+ candidates+ .iter()+ .find(|(top, _)| {+ candidates+ .iter()+ .all(|(other, _)| is_ancestor(top.pid, other.pid))+ })+ .map(|(entry, agent)| (entry.pid, agent.clone()))+}++/// Windows replacement for the unix leader probe: tree-based agent+/// selection first, and every miss falls back to the youngest-console+/// heuristic behind `get_foreground_process_name`, so behavior is never+/// worse than before this module existed. Returns `(leader_path, agent)`+/// as `identify::probe` caches them; with an agent selected, the leader+/// path is that agent's executable, which also gives the contract's+/// leader-equality liveness check a real signal on Windows.+#[cfg(windows)]+pub(crate) fn probe_pane(+ pane: &dyn crate::pane::Pane,+ policy: crate::pane::CachePolicy,+) -> (Option<String>, Option<String>) {+ if let (Some(root), Some(table)) = (pane.root_process_id(), facts::shared_process_table()) {+ let lookup = |name: &str| super::engine::manifest_id_for_alias(name);+ let mut identify_entry = |entry: &ProcessTableEntry| {+ // Name first (free); argv — a PEB read — only when the name+ // is a generic runtime.+ let mut argv = || procinfo::LocalProcessInfo::argv_for_pid(entry.pid);+ super::proc_match::identify(&entry.name, &mut argv, &lookup)+ };+ if let Some((pid, agent)) = select_agent(table.as_slice(), root, &mut identify_entry) {+ let leader_path = procinfo::LocalProcessInfo::executable_path(pid)+ .map(|path| path.to_string_lossy().to_string())+ .or_else(|| {+ table+ .iter()+ .find(|entry| entry.pid == pid)+ .map(|entry| entry.name.clone())+ });+ return (leader_path, Some(agent));+ }+ }+ let leader_path = pane+ .get_foreground_process_name(policy)+ .map(super::identify::normalize_executable_path);+ let agent = leader_path.as_deref().and_then(|path| {+ let mut argv = || pane.get_foreground_process_argv(crate::pane::CachePolicy::AllowStale);+ super::proc_match::identify(path, &mut argv, &|name| {+ super::engine::manifest_id_for_alias(name)+ })+ });+ (leader_path, agent)+}++#[cfg(windows)]+pub(crate) mod facts {+ use parking_lot::Mutex;+ use std::sync::Arc;+ use std::time::{Duration, Instant};++ /// One process-table snapshot serves every pane; herdr's number. At+ /// hundreds of panes this is what keeps identification from turning+ /// into hundreds of Toolhelp32 walks per sweep.+ const SNAPSHOT_TTL: Duration = Duration::from_millis(250);++ static SNAPSHOT: Mutex<Option<(Instant, Arc<Vec<procinfo::ProcessTableEntry>>)>> =+ Mutex::new(None);++ pub(crate) fn shared_process_table() -> Option<Arc<Vec<procinfo::ProcessTableEntry>>> {+ let mut slot = SNAPSHOT.lock();+ if let Some((at, table)) = slot.as_ref() {+ if at.elapsed() < SNAPSHOT_TTL {+ return Some(table.clone());+ }+ }+ let table = Arc::new(procinfo::process_table()?);+ *slot = Some((Instant::now(), table.clone()));+ Some(table)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn entry(pid: u32, ppid: u32, name: &str) -> ProcessTableEntry {+ ProcessTableEntry {+ pid,+ ppid,+ name: name.to_string(),+ }+ }++ fn ident(entry: &ProcessTableEntry) -> Option<String> {+ match entry.name.as_str() {+ "claude.exe" => Some("claude".to_string()),+ "codex.exe" => Some("codex".to_string()),+ _ => None,+ }+ }++ #[test]+ fn topmost_agent_beats_its_own_children() {+ // shell(1) -> claude(2) -> node mcp(3) -> codex helper(4)+ let table = vec![+ entry(1, 0, "pwsh.exe"),+ entry(2, 1, "claude.exe"),+ entry(3, 2, "node.exe"),+ entry(4, 3, "codex.exe"),+ ];+ assert_eq!(+ select_agent(&table, 1, &mut ident),+ Some((2, "claude".to_string()))+ );+ }++ #[test]+ fn sibling_agents_are_ambiguous_and_select_nothing() {+ let table = vec![+ entry(1, 0, "pwsh.exe"),+ entry(2, 1, "claude.exe"),+ entry(3, 1, "codex.exe"),+ ];+ assert_eq!(select_agent(&table, 1, &mut ident), None);+ }++ #[test]+ fn processes_outside_the_pane_tree_do_not_leak_in() {+ let table = vec![+ entry(1, 0, "pwsh.exe"),+ entry(2, 1, "node.exe"),+ // Another pane's claude, unrelated ancestry.+ entry(9, 7, "claude.exe"),+ ];+ assert_eq!(select_agent(&table, 1, &mut ident), None);+ }++ #[test]+ fn pid_reuse_loops_terminate() {+ // 2 and 3 point at each other. The property under test is+ // termination; in a fabricated cycle both claim ancestry and the+ // walk-order-first candidate (the root) wins deterministically.+ let table = vec![+ entry(2, 3, "claude.exe"),+ entry(3, 2, "codex.exe"),+ ];+ assert_eq!(+ select_agent(&table, 2, &mut ident),+ Some((2, "claude".to_string()))+ );+ }++ #[test]+ fn the_root_itself_can_be_the_agent() {+ let table = vec![entry(5, 1, "claude.exe"), entry(6, 5, "node.exe")];+ assert_eq!(+ select_agent(&table, 5, &mut ident),+ Some((5, "claude".to_string()))+ );+ }+}diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex b3fe4466..5457ce9f 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -607,6 +607,13 @@ impl Pane for LocalPane {None}+ fn root_process_id(&self) -> Option<u32> {+ match &*self.process.lock() {+ ProcessState::Running { pid, .. } => *pid,+ _ => None,+ }+ }+fn can_close_without_prompting(&self, _reason: CloseReason) -> bool {if let Some(info) = self.divine_process_list(CachePolicy::FetchImmediate) {log::trace!(diff --git a/mux/src/pane.rs b/mux/src/pane.rsindex 3f1425eb..267dea6a 100644--- a/mux/src/pane.rs+++ b/mux/src/pane.rs@@ -389,6 +389,12 @@ pub trait Pane: Downcast + Send + Sync {fn get_foreground_process_argv(&self, _policy: CachePolicy) -> Option<Vec<String>> {None}+ /// The pane's root (pty child) process id, when the platform tracks+ /// one. Windows agent identification walks the process tree from+ /// here — there is no foreground-group concept to ask instead.+ fn root_process_id(&self) -> Option<u32> {+ None+ }fn get_foreground_process_info(&self,_policy: CachePolicy,diff --git a/procinfo/Cargo.toml b/procinfo/Cargo.tomlindex e695a35a..f93c8bcd 100644--- a/procinfo/Cargo.toml+++ b/procinfo/Cargo.toml@@ -17,6 +17,9 @@ wezterm-dynamic = { workspace=true, optional = true, features=["std"]}[target."cfg(windows)".dependencies]ntapi.workspace = true+# The full set this crate uses by itself: a bare `cargo check -p+# procinfo --target x86_64-pc-windows-msvc` must build without another+# workspace crate's features papering over a gap here.winapi = { workspace=true, features = ["handleapi","memoryapi",@@ -24,5 +27,6 @@ winapi = { workspace=true, features = ["processthreadsapi","shellapi","tlhelp32",+ "winbase",]}diff --git a/procinfo/src/lib.rs b/procinfo/src/lib.rsindex bfebcb7b..ba987120 100644--- a/procinfo/src/lib.rs+++ b/procinfo/src/lib.rs@@ -25,6 +25,27 @@ pub enum LocalProcessStatus {Unknown,}+/// One row of the system process table: ancestry facts only, gathered+/// without opening a handle to any process (unlike `with_root_pid`,+/// which opens every process it touches). Windows-only in practice;+/// other platforms return `None` from [`process_table`].+#[derive(Debug, Clone)]+pub struct ProcessTableEntry {+ pub pid: u32,+ pub ppid: u32,+ /// The executable image name as the snapshot reports it+ /// (`szExeFile`, e.g. "node.exe").+ pub name: String,+}++#[cfg(windows)]+pub use windows::process_table;++#[cfg(not(windows))]+pub fn process_table() -> Option<Vec<ProcessTableEntry>> {+ None+}+#[derive(Debug, Clone)]#[cfg_attr(feature = "lua", derive(FromDynamic, ToDynamic))]pub struct LocalProcessInfo {diff --git a/procinfo/src/windows.rs b/procinfo/src/windows.rsindex f82caf50..da6bcad2 100644--- a/procinfo/src/windows.rs+++ b/procinfo/src/windows.rs@@ -342,6 +342,32 @@ impl Drop for ProcHandle {}}+/// See [`crate::ProcessTableEntry`]: one Toolhelp32 pass, no per-process+/// handles.+pub fn process_table() -> Option<Vec<crate::ProcessTableEntry>> {+ let entries = Snapshot::entries();+ if entries.is_empty() {+ return None;+ }+ Some(+ entries+ .iter()+ .map(|entry| {+ let len = entry+ .szExeFile+ .iter()+ .position(|&c| c == 0)+ .unwrap_or(entry.szExeFile.len());+ crate::ProcessTableEntry {+ pid: entry.th32ProcessID,+ ppid: entry.th32ParentProcessID,+ name: String::from_utf16_lossy(&entry.szExeFile[..len]),+ }+ })+ .collect(),+ )+}+impl LocalProcessInfo {pub fn current_working_dir(pid: u32) -> Option<PathBuf> {log::trace!("current_working_dir({})", pid);