This repository has been archived on 2026-10-08. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
maestro/crates/maestro-daemon/src/tmux.rs
T
naps62-yolo 53660407e3
ci / web (push) Successful in 28s
ci / rust (push) Successful in 2m34s
feat(maestro): add a process-compose dev stack (#52)
2026-08-23 10:02:09 +01:00

629 lines
22 KiB
Rust

//! Subprocess wrapper around the `tmux` binary.
//!
//! All sessions managed through this wrapper are named `maestro-<uuid>` so that
//! the daemon can recover its own sessions on restart (and ignore foreign ones).
use std::collections::BTreeMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use uuid::Uuid;
/// Prefix used for every tmux session the daemon owns.
pub const SESSION_PREFIX: &str = "maestro-";
#[derive(Debug, thiserror::Error)]
pub enum TmuxError {
#[error("failed to spawn tmux: {0}")]
Spawn(#[from] std::io::Error),
#[error("tmux exited with code {code}: {stderr}")]
NonZero { code: i32, stderr: String },
}
/// Handle to a tmux server. Cheap to clone.
#[derive(Debug, Clone)]
pub struct Tmux {
binary: PathBuf,
socket_name: Option<String>,
tmpdir: Option<PathBuf>,
}
impl Default for Tmux {
fn default() -> Self {
Self {
binary: PathBuf::from("tmux"),
socket_name: None,
tmpdir: None,
}
}
}
impl Tmux {
pub fn new() -> Self {
Self::default()
}
/// Pass `-L <name>` to every tmux invocation. Useful to isolate test
/// servers from the user's normal tmux session.
pub fn with_socket(mut self, name: impl Into<String>) -> Self {
self.socket_name = Some(name.into());
self
}
/// Set `TMUX_TMPDIR` for every tmux invocation. The tmux server keeps its
/// socket under this directory.
pub fn with_tmpdir(mut self, dir: impl Into<PathBuf>) -> Self {
self.tmpdir = Some(dir.into());
self
}
pub fn socket_name(&self) -> Option<&str> {
self.socket_name.as_deref()
}
pub fn tmpdir(&self) -> Option<&Path> {
self.tmpdir.as_deref()
}
fn cmd(&self) -> Command {
let mut c = Command::new(&self.binary);
if let Some(s) = &self.socket_name {
c.arg("-L").arg(s);
}
if let Some(d) = &self.tmpdir {
c.env("TMUX_TMPDIR", d);
}
// A daemon started from inside a tmux pane inherits `TMUX`, and tmux
// resolves that ahead of `TMUX_TMPDIR` — so without this the daemon
// drives the developer's own server and `tmux_tmpdir` does nothing.
c.env_remove("TMUX");
c
}
/// `tmux set-option -g default-terminal tmux-256color \; new-session -d -e TERM=xterm-256color -e COLORTERM=truecolor -s maestro-<id> -c <cwd> <command>`.
///
/// `command` is wrapped by [`login_shell_command`] (so the spawned process
/// inherits the user's rc-configured PATH) and passed as a single shell-line
/// argument to tmux, which invokes it via `$SHELL -c`. Two layers ensure
/// attach clients see color:
/// the `-e TERM=…`/`COLORTERM=…` flags populate the spawned shell's env
/// even when `maestrod` runs from a stripped systemd unit, and the chained
/// `set-option -g default-terminal tmux-256color` overrides tmux's
/// distro-default `screen` (8-color) terminfo for the pane process. The
/// `set-option` is chained into the same tmux invocation because a
/// stand-alone server with no sessions exits immediately under tmux's
/// default `exit-empty on`.
pub fn new_session(&self, id: Uuid, cwd: &Path, command: &str) -> Result<(), TmuxError> {
let name = session_name(id);
let command = login_shell_command(env::var_os("SHELL").as_deref(), command);
let out = self
.cmd()
.args(new_session_args(
&name,
cwd,
&command,
&BTreeMap::new(),
None,
))
.output()?;
check(out)
}
/// Like [`Self::new_session`], but chains `pipe-pane -t maestro-<id>
/// <sink_command>` into the same tmux invocation. Use this from
/// `SessionManager::create` so the pipe is in place before the freshly
/// `exec`-ed child writes its first byte; calling `new_session` + a
/// separate `pipe_pane` opens a window in which initial output is
/// silently dropped (NAP-253).
pub fn new_session_piped(
&self,
id: Uuid,
cwd: &Path,
command: &str,
session_env: &BTreeMap<String, String>,
sink_command: &str,
) -> Result<(), TmuxError> {
let name = session_name(id);
let command = login_shell_command(env::var_os("SHELL").as_deref(), command);
let out = self
.cmd()
.args(new_session_args(
&name,
cwd,
&command,
session_env,
Some(sink_command),
))
.output()?;
check(out)
}
/// `tmux kill-session -t maestro-<id>`.
pub fn kill_session(&self, id: Uuid) -> Result<(), TmuxError> {
let name = session_name(id);
let out = self.cmd().args(["kill-session", "-t", &name]).output()?;
check(out)
}
/// `tmux list-sessions -F '#{session_name}'`, filtered to `maestro-*` and
/// parsed back into UUIDs. Returns an empty vector if no tmux server is
/// running (so callers don't need to special-case startup).
pub fn list_sessions(&self) -> Result<Vec<Uuid>, TmuxError> {
let out = self
.cmd()
.args(["list-sessions", "-F", "#{session_name}"])
.output()?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
if is_no_server_error(&stderr) {
return Ok(Vec::new());
}
return Err(TmuxError::NonZero {
code: out.status.code().unwrap_or(-1),
stderr: stderr.into_owned(),
});
}
let stdout = String::from_utf8_lossy(&out.stdout);
let mut ids = Vec::new();
for line in stdout.lines() {
if let Some(rest) = line.strip_prefix(SESSION_PREFIX) {
if let Ok(u) = Uuid::parse_str(rest) {
ids.push(u);
}
}
}
Ok(ids)
}
/// `tmux list-panes -t maestro-<id> -F '#{pane_pid} #{pane_current_command}
/// #{pane_tty} #{pane_current_path}'` for the session's (single) pane. Used
/// by the activity watcher (NAP-340) to learn the foreground command, the
/// pane's process, its tty, and its *current* working directory. The path is
/// the last field, so [`parse_pane_line`] takes the first three
/// space-separated tokens and keeps the remainder verbatim — a cwd that
/// itself contains spaces survives intact. Returns `Ok(None)` when the
/// session/pane is gone or tmux isn't running, so the watcher degrades to
/// "unknown" rather than erroring.
pub fn pane_info(&self, id: Uuid) -> Result<Option<PaneInfo>, TmuxError> {
let name = session_name(id);
let out = self
.cmd()
.args([
"list-panes",
"-t",
&name,
"-F",
"#{pane_pid} #{pane_current_command} #{pane_tty} #{pane_current_path}",
])
.output()?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
// No server, or the session/pane vanished between the liveness check
// and now — both are "no info", not a hard error.
if is_no_server_error(&stderr) || stderr.contains("can't find") {
return Ok(None);
}
return Err(TmuxError::NonZero {
code: out.status.code().unwrap_or(-1),
stderr: stderr.into_owned(),
});
}
let stdout = String::from_utf8_lossy(&out.stdout);
Ok(stdout.lines().next().and_then(parse_pane_line))
}
/// `tmux send-keys -t maestro-<id> -l <bytes>`. The `-l` flag tells tmux to
/// treat the payload as literal input (no key-name translation), which is
/// what we want for forwarded PTY input.
pub fn send_keys(&self, id: Uuid, bytes: &[u8]) -> Result<(), TmuxError> {
let name = session_name(id);
let mut arg = OsString::new();
arg.push(OsStr::from_bytes(bytes));
let out = self
.cmd()
.args(["send-keys", "-t", &name, "-l"])
.arg(arg)
.output()?;
check(out)
}
/// `tmux pipe-pane -t maestro-<id> '<sink_command>'`.
///
/// `sink_command` is a shell command that receives pane output on stdin
/// (e.g. `cat >> /tmp/sess.log`). Without `-o`, tmux closes any pipe
/// already running on the pane before opening this one — important on
/// `SessionManager::recover`, where the previous daemon process may have
/// left a `pipe-pane` writing to a FIFO that no one is reading anymore.
pub fn pipe_pane(&self, id: Uuid, sink_command: &str) -> Result<(), TmuxError> {
let name = session_name(id);
let out = self
.cmd()
.args(["pipe-pane", "-t", &name, sink_command])
.output()?;
check(out)
}
/// `tmux resize-window -t maestro-<id> -x <cols> -y <rows>`.
pub fn resize_window(&self, id: Uuid, cols: u16, rows: u16) -> Result<(), TmuxError> {
let name = session_name(id);
let out = self
.cmd()
.args([
"resize-window",
"-t",
&name,
"-x",
&cols.to_string(),
"-y",
&rows.to_string(),
])
.output()?;
check(out)
}
/// `tmux kill-server`. Best-effort cleanup used mostly by tests.
pub fn kill_server(&self) -> Result<(), TmuxError> {
let out = self.cmd().arg("kill-server").output()?;
if out.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&out.stderr);
if is_no_server_error(&stderr) {
return Ok(());
}
Err(TmuxError::NonZero {
code: out.status.code().unwrap_or(-1),
stderr: stderr.into_owned(),
})
}
}
/// Phrasings tmux uses for "there is no server on this socket". They vary by
/// version, and `list_sessions` turning one of these into an `Err` stops the
/// liveness watcher reaping for that pass — so a missing phrasing is silent.
const NO_SERVER_PHRASES: &[&str] = &[
"no server running",
"no sessions",
"error connecting",
// tmux >= 3.7 when the server shuts down while this client is connected,
// which is exactly what killing the last session does.
"server exited unexpectedly",
];
/// True if tmux's stderr indicates "there is no tmux server running on this
/// socket" (multiple phrasings across versions).
fn is_no_server_error(stderr: &str) -> bool {
NO_SERVER_PHRASES.iter().any(|p| stderr.contains(p))
}
/// A session pane's process id, foreground command, controlling tty, and
/// current working directory, as reported by `tmux list-panes` (NAP-340).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaneInfo {
pub pane_pid: i32,
pub command: String,
pub tty: String,
/// `#{pane_current_path}` — the pane's live cwd. Empty if tmux reported none.
pub current_path: String,
}
/// Parse one `#{pane_pid} #{pane_current_command} #{pane_tty} #{pane_current_path}`
/// line. `pane_pid`, `pane_current_command`, and `pane_tty` are single tokens, so
/// we split on the first three spaces and treat the remainder as the path —
/// which keeps a cwd intact even when it contains spaces. The path field is
/// absent on older format strings, in which case it defaults to empty.
fn parse_pane_line(line: &str) -> Option<PaneInfo> {
let mut parts = line.splitn(4, ' ');
let pane_pid: i32 = parts.next()?.trim().parse().ok()?;
let command = parts.next()?;
let tty = parts.next()?;
let current_path = parts.next().unwrap_or("");
if command.is_empty() {
return None;
}
Some(PaneInfo {
pane_pid,
command: command.to_string(),
tty: tty.to_string(),
current_path: current_path.to_string(),
})
}
pub fn session_name(id: Uuid) -> String {
format!("{SESSION_PREFIX}{id}")
}
/// Wrap a session command so it runs through the user's login + interactive
/// shell.
///
/// `maestrod` usually runs from a stripped systemd user unit whose `PATH`
/// lacks per-user toolchain dirs (`~/.local/bin`, `~/.opencode/bin`, …). tmux
/// runs a new-session command via `$SHELL -c` *non-interactively*, so a bare
/// command like `claude` or `opencode` — which lives only on the PATH the user
/// exports from `~/.zshrc` / `~/.bashrc` — fails with "command not found".
/// Re-execing an interactive login shell sources that rc first, restoring the
/// PATH the user sees in a normal terminal. `exec` keeps the process tree flat
/// so pane-command inference still sees the real child.
///
/// Falls back to the bare command when `$SHELL` is unset/empty (nothing better
/// to wrap with).
fn login_shell_command(shell: Option<&OsStr>, command: &str) -> String {
match shell {
Some(shell) if !shell.is_empty() => {
format!(
"exec {} -lic {}",
shell.to_string_lossy(),
single_quote(command)
)
}
_ => command.to_string(),
}
}
/// POSIX single-quote a string: wrap in `'…'`, rewriting embedded `'` as
/// `'\''`. Safe to splice into a shell command line.
fn single_quote(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('\'');
for ch in s.chars() {
if ch == '\'' {
out.push_str("'\\''");
} else {
out.push(ch);
}
}
out.push('\'');
out
}
/// Args passed to `tmux` for `new_session` / `new_session_piped`, excluding
/// the binary itself and any socket/tmpdir flags injected by [`Tmux::cmd`].
/// When `pipe_sink` is `Some`, a chained `pipe-pane -t <name> <sink>` is
/// appended so the pipe attaches in the same tmux invocation that creates
/// the session.
fn new_session_args(
name: &str,
cwd: &Path,
command: &str,
env: &BTreeMap<String, String>,
pipe_sink: Option<&str>,
) -> Vec<OsString> {
let mut args = vec![
OsString::from("set-option"),
OsString::from("-g"),
OsString::from("default-terminal"),
OsString::from("tmux-256color"),
OsString::from(";"),
OsString::from("new-session"),
OsString::from("-d"),
OsString::from("-e"),
OsString::from("TERM=xterm-256color"),
OsString::from("-e"),
OsString::from("COLORTERM=truecolor"),
OsString::from("-s"),
OsString::from(name),
OsString::from("-c"),
cwd.as_os_str().to_os_string(),
];
// Caller-supplied environment. Sorted so the argv is deterministic, and
// therefore assertable.
for (k, v) in env {
args.push(OsString::from("-e"));
args.push(OsString::from(format!("{k}={v}")));
}
args.push(OsString::from(command));
if let Some(sink) = pipe_sink {
args.extend([
OsString::from(";"),
OsString::from("pipe-pane"),
OsString::from("-t"),
OsString::from(name),
OsString::from(sink),
]);
}
args
}
fn check(out: Output) -> Result<(), TmuxError> {
if out.status.success() {
Ok(())
} else {
Err(TmuxError::NonZero {
code: out.status.code().unwrap_or(-1),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every phrasing must be recognised: an unmatched one makes
/// `list_sessions` fail, and a failed pass reaps nothing.
#[test]
fn new_session_args_emit_sorted_env_flags_before_the_command() {
let env: BTreeMap<String, String> = [
("ZED".to_string(), "9".to_string()),
("ALPHA".to_string(), "1".to_string()),
]
.into_iter()
.collect();
let args = new_session_args("maestro-x", Path::new("/tmp"), "bash", &env, None);
let flat: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let alpha = flat.iter().position(|a| a == "ALPHA=1").expect("ALPHA");
let zed = flat.iter().position(|a| a == "ZED=9").expect("ZED");
let command = flat.iter().rposition(|a| a == "bash").expect("command");
assert!(alpha < zed, "env flags must be sorted for a stable argv");
assert!(zed < command, "env must precede the command argument");
assert_eq!(flat[alpha - 1], "-e");
assert_eq!(flat[zed - 1], "-e");
}
/// `TMUX` beats `TMUX_TMPDIR` when tmux looks for a server, so leaving an
/// inherited one in place would silently ignore the configured tmpdir.
#[test]
fn cmd_clears_an_inherited_tmux_and_sets_the_configured_tmpdir() {
let tmux = Tmux::new().with_tmpdir("/run/maestro-dev");
let cmd = tmux.cmd();
let envs: Vec<_> = cmd.get_envs().collect();
assert!(
envs.contains(&(OsStr::new("TMUX"), None)),
"TMUX must be removed, got {envs:?}"
);
assert!(
envs.contains(&(
OsStr::new("TMUX_TMPDIR"),
Some(OsStr::new("/run/maestro-dev"))
)),
"TMUX_TMPDIR must be set, got {envs:?}"
);
}
/// The removal is unconditional: a daemon manages its own server whether or
/// not a tmpdir was configured.
#[test]
fn cmd_clears_an_inherited_tmux_without_a_configured_tmpdir() {
let cmd = Tmux::new().cmd();
let envs: Vec<_> = cmd.get_envs().collect();
assert!(
envs.contains(&(OsStr::new("TMUX"), None)),
"TMUX must be removed, got {envs:?}"
);
}
#[test]
fn is_no_server_error_matches_every_known_phrasing() {
for phrase in NO_SERVER_PHRASES {
assert!(is_no_server_error(phrase), "unmatched: {phrase}");
assert!(
is_no_server_error(&format!("{phrase}\n")),
"unmatched with trailing newline: {phrase}"
);
}
}
#[test]
fn is_no_server_error_rejects_unrelated_failures() {
assert!(!is_no_server_error("can't find session: maestro-x"));
assert!(!is_no_server_error("usage: kill-session"));
assert!(!is_no_server_error(""));
}
#[test]
fn parse_pane_line_splits_pid_command_tty_path() {
let p = parse_pane_line("12345 claude /dev/pts/3 /home/naps62/maestro").unwrap();
assert_eq!(p.pane_pid, 12345);
assert_eq!(p.command, "claude");
assert_eq!(p.tty, "/dev/pts/3");
assert_eq!(p.current_path, "/home/naps62/maestro");
}
#[test]
fn parse_pane_line_keeps_spaces_in_path() {
// The path is the trailing field (split on the first three spaces only),
// so spaces inside it survive intact.
let p = parse_pane_line("9 bash /dev/pts/0 /home/naps62/My Projects/x").unwrap();
assert_eq!(p.current_path, "/home/naps62/My Projects/x");
}
#[test]
fn parse_pane_line_tolerates_missing_path_field() {
// A daemon/tmux that omits the path field still yields the other fields.
let p = parse_pane_line("12345 claude /dev/pts/3").unwrap();
assert_eq!(p.command, "claude");
assert_eq!(p.current_path, "");
}
#[test]
fn parse_pane_line_rejects_malformed() {
assert!(parse_pane_line("").is_none());
assert!(parse_pane_line("notapid bash /dev/pts/0").is_none());
}
#[test]
fn new_session_args_pass_256color_env_and_default_terminal() {
let args = new_session_args(
"maestro-abc",
Path::new("/tmp/proj"),
"sleep 30",
&BTreeMap::new(),
None,
);
let strs: Vec<&str> = args.iter().map(|s| s.to_str().unwrap()).collect();
assert_eq!(
strs,
vec![
"set-option",
"-g",
"default-terminal",
"tmux-256color",
";",
"new-session",
"-d",
"-e",
"TERM=xterm-256color",
"-e",
"COLORTERM=truecolor",
"-s",
"maestro-abc",
"-c",
"/tmp/proj",
"sleep 30",
]
);
}
#[test]
fn login_shell_command_wraps_in_interactive_login_shell() {
assert_eq!(
login_shell_command(Some(OsStr::new("/usr/bin/zsh")), "claude"),
"exec /usr/bin/zsh -lic 'claude'"
);
}
#[test]
fn login_shell_command_quotes_command_with_spaces_and_quotes() {
assert_eq!(
login_shell_command(Some(OsStr::new("/bin/bash")), "sh -c 'echo hi'"),
r#"exec /bin/bash -lic 'sh -c '\''echo hi'\'''"#
);
}
#[test]
fn login_shell_command_passes_through_without_shell() {
assert_eq!(login_shell_command(None, "claude"), "claude");
assert_eq!(
login_shell_command(Some(OsStr::new("")), "claude"),
"claude"
);
}
#[test]
fn new_session_args_chain_pipe_pane_when_sink_present() {
let args = new_session_args(
"maestro-abc",
Path::new("/tmp/proj"),
"sleep 30",
&BTreeMap::new(),
Some("cat >> '/tmp/fifo'"),
);
let strs: Vec<&str> = args.iter().map(|s| s.to_str().unwrap()).collect();
// The pipe-pane chain must come after new-session in the same argv
// so tmux attaches the pipe before the child writes its first byte
// (NAP-253).
assert_eq!(
&strs[strs.len() - 5..],
&[";", "pipe-pane", "-t", "maestro-abc", "cat >> '/tmp/fifo'"]
);
}
}