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 946aa384a0
ci / rust (push) Failing after 3s
feat(maestro): add daemon tmux/sidecar/worktree primitives
Local primitives for `maestrod`, no network code yet:

- `tmux`: subprocess wrapper around new-session, kill-session,
  list-sessions (filtered to maestro-*), send-keys -l, pipe-pane -o,
  resize-window, kill-server.
- `sidecar`: atomic JSON metadata store keyed by session UUID, with
  load_all for daemon restart recovery.
- `worktree`: `git worktree add -b` with collision-proof generated paths
  and `git worktree remove --force` for cleanup_on_kill.

Integration tests use real tmux (isolated via unique socket + temp
TMUX_TMPDIR) and real git (tmpdir repo).

Closes NAP-212.
2026-05-24 13:02:41 +00:00

218 lines
6.7 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::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);
}
c
}
/// `tmux new-session -d -s maestro-<id> -c <cwd> <command>`.
///
/// `command` is passed as a single shell-line argument to tmux, which
/// invokes it via `$SHELL -c`.
pub fn new_session(&self, id: Uuid, cwd: &Path, command: &str) -> Result<(), TmuxError> {
let name = session_name(id);
let out = self
.cmd()
.args(["new-session", "-d", "-s", &name, "-c"])
.arg(cwd)
.arg(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 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> -o '<sink_command>'`.
///
/// `sink_command` is a shell command that receives pane output on stdin
/// (e.g. `cat >> /tmp/sess.log`). The `-o` flag makes the call idempotent:
/// if a pipe is already running on the pane, this is a no-op.
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, "-o", 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(),
})
}
}
/// 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 {
stderr.contains("no server running")
|| stderr.contains("no sessions")
|| stderr.contains("error connecting")
}
pub fn session_name(id: Uuid) -> String {
format!("{SESSION_PREFIX}{id}")
}
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(),
})
}
}