use crate::error::SpriteError;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::process::Command;
#[allow(dead_code)]
pub fn create_session(name: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["new-session", "-d", "-s", name])
.output()
.with_context(|| "Failed to create tmux session. Is tmux installed?")?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!("Failed to create tmux session '{}'", name),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
pub fn session_exists(name: &str) -> Result<bool> {
let output = Command::new("tmux")
.args(["has-session", "-t", name])
.output()
.with_context(|| "Failed to check tmux session existence")?;
Ok(output.status.success())
}
#[allow(dead_code)]
pub fn session_ready_with_panes(name: &str, expected_panes: usize) -> Result<bool> {
if !session_exists(name)? {
return Ok(false);
}
match get_session_panes(name) {
Ok(panes) => {
if panes.len() >= expected_panes {
Ok(true)
} else {
Ok(false)
}
}
Err(_) => {
Ok(false)
}
}
}
#[allow(dead_code)]
pub fn kill_session(name: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["kill-session", "-t", name])
.output()
.with_context(|| format!("Failed to kill tmux session '{}'", name))?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!("Failed to kill tmux session '{}'", name),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
pub fn kill_session_force(name: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["kill-session", "-t", name])
.output()
.with_context(|| format!("Failed to kill tmux session '{}'", name))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("session not found") && !stderr.contains("can't find session") {
return Err(SpriteError::tmux_with_source(
format!("Failed to kill tmux session '{}'", name),
stderr,
)
.into());
}
}
Ok(())
}
#[allow(dead_code)]
pub fn attach_session(name: &str) -> Result<()> {
use std::process::Stdio;
let status = Command::new("tmux")
.args(["attach", "-t", name])
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.with_context(|| format!("Failed to attach to tmux session '{}'", name))?;
if !status.success() {
return Err(SpriteError::tmux(
format!("Failed to attach to tmux session '{}'. This may be due to terminal compatibility. Try: tmux attach -t {} or sprite start --force", name, name),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn list_sessions() -> Result<Vec<SessionInfo>> {
let output = Command::new("tmux")
.args(["list-sessions"])
.output()
.with_context(|| "Failed to list tmux sessions")?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
"Failed to list tmux sessions",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let sessions_str = String::from_utf8_lossy(&output.stdout);
parse_sessions_list(&sessions_str)
}
#[derive(Debug, Clone)]
pub struct SessionInfo {
#[allow(dead_code)]
pub name: String,
#[allow(dead_code)]
pub windows: usize,
#[allow(dead_code)]
pub panes: usize,
#[allow(dead_code)]
pub created: String,
#[allow(dead_code)]
pub attached: bool,
}
#[allow(dead_code)]
fn parse_sessions_list(output: &str) -> Result<Vec<SessionInfo>> {
let mut sessions = Vec::new();
for line in output.lines() {
if line.trim().is_empty() {
continue;
}
if let Some((name, info_part)) = line.split_once(':') {
let name = name.to_string();
let windows = info_part
.split_whitespace()
.next()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let created = info_part
.find("(created ")
.and_then(|i| {
let start = i + 9;
info_part[start..]
.find(')')
.map(|j| info_part[start..j].to_string())
})
.unwrap_or_else(|| "unknown".to_string());
let attached = info_part.contains("[attached]");
let panes = windows;
sessions.push(SessionInfo {
name,
windows,
panes,
created,
attached,
});
}
}
Ok(sessions)
}
pub fn create_window(session: &str, window_name: &str) -> Result<String> {
let output = Command::new("tmux")
.args(["new-window", "-t", session, "-n", window_name])
.output()
.with_context(|| {
format!(
"Failed to create window '{}' in session '{}'",
window_name, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to create window '{}' in session '{}'",
window_name, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let window_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(window_id)
}
#[allow(dead_code)]
pub fn split_window_vertical(session: &str, target: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["split-window", "-t", session, "-v", "-P", target])
.output()
.with_context(|| format!("Failed to split window vertically in session '{}'", session))?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!("Failed to split window vertically in session '{}'", session),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn split_window_horizontal(session: &str, target: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["split-window", "-t", session, "-h", "-P", target])
.output()
.with_context(|| {
format!(
"Failed to split window horizontally in session '{}'",
session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to split window horizontally in session '{}'",
session
),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
.into());
}
Ok(())
}
fn build_target_spec(session: &str, target: &str) -> String {
if target.starts_with('%') || target.contains(':') {
target.to_string()
} else if target.chars().all(|c| c.is_ascii_digit()) {
format!("{}:.{}", session, target)
} else {
format!("{}:{}", session, target)
}
}
#[allow(dead_code)]
pub fn send_keys(session: &str, target: &str, command: &str) -> Result<()> {
let target_spec = build_target_spec(session, target);
let output = Command::new("tmux")
.args(["send-keys", "-t", &target_spec, command, "C-m"])
.output()
.with_context(|| {
format!(
"Failed to send keys to pane '{}' in session '{}'",
target, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to send keys to pane '{}' in session '{}'",
target, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn capture_pane(session: &str, target: &str) -> Result<String> {
let target_spec = build_target_spec(session, target);
let output = Command::new("tmux")
.args(["capture-pane", "-p", "-t", &target_spec])
.output()
.with_context(|| {
format!(
"Failed to capture pane '{}' in session '{}'",
target, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to capture pane '{}' in session '{}'",
target, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
#[allow(dead_code)]
pub fn select_layout(session: &str, target: &str, layout: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["select-layout", "-t", session, "-P", target, layout])
.output()
.with_context(|| {
format!(
"Failed to select layout '{}' for pane '{}' in session '{}'",
layout, target, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to select layout '{}' for pane '{}' in session '{}'",
layout, target, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn get_layout(session: &str, target: &str) -> Result<String> {
let output = Command::new("tmux")
.args([
"display-message",
"-p",
"-t",
session,
"-F '#{window_layout}'",
target,
])
.output()
.with_context(|| {
format!(
"Failed to get layout for pane '{}' in session '{}'",
target, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to get layout for pane '{}' in session '{}'",
target, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
#[allow(dead_code)]
pub fn is_tmux_available() -> Result<bool> {
let output = Command::new("tmux")
.arg("-V")
.output()
.with_context(|| "Failed to check tmux availability")?;
Ok(output.status.success())
}
#[allow(dead_code)]
pub fn get_tmux_version() -> Result<String> {
let output = Command::new("tmux")
.arg("-V")
.output()
.with_context(|| "Failed to get tmux version")?;
if !output.status.success() {
return Err(SpriteError::tmux("tmux not found or not executable").into());
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
#[allow(dead_code)]
pub fn set_environment(session: &str, env_vars: &HashMap<String, String>) -> Result<()> {
for (key, value) in env_vars {
let output = Command::new("tmux")
.args([
"set-environment",
"-t",
session,
&format!("{}={}", key, value),
])
.output()
.with_context(|| {
format!(
"Failed to set environment variable '{}' for session '{}'",
key, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to set environment variable '{}' for session '{}'",
key, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
}
Ok(())
}
#[allow(dead_code)]
pub fn execute_profile_script(session: &str, script_path: &std::path::Path) -> Result<()> {
execute_profile_script_with_agent_count(session, script_path, 3)
}
pub fn execute_profile_script_with_agent_count(
session: &str,
script_path: &std::path::Path,
agent_count: u32,
) -> Result<()> {
if !script_path.exists() {
return Err(SpriteError::filesystem(
format!("Profile script not found: {}", script_path.display()),
script_path.display().to_string(),
)
.into());
}
println!(
"📜 Executing profile script: {} with {} agents",
script_path.display(),
agent_count
);
let output = Command::new("bash")
.arg(script_path)
.env("SPRITE_SESSION", session)
.env("AGENT_COUNT", agent_count.to_string())
.output()
.with_context(|| {
format!(
"Failed to execute profile script: {}",
script_path.display()
)
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
return Err(SpriteError::tmux_with_source(
format!("Profile script execution failed: {}", script_path.display()),
format!("stdout: {}\nstderr: {}", stdout, stderr),
)
.into());
}
println!(" ✅ Profile script executed successfully");
std::thread::sleep(std::time::Duration::from_millis(200));
Ok(())
}
pub fn get_session_panes(session: &str) -> Result<Vec<PaneInfo>> {
get_session_panes_with_retry(session, 3)
}
pub fn get_session_panes_with_retry(session: &str, max_retries: u32) -> Result<Vec<PaneInfo>> {
const PANE_FORMAT: &str =
"#{pane_index}|#{pane_id}|#{pane_current_path}|#{pane_current_command}";
for attempt in 0..max_retries {
let output = Command::new("tmux")
.args(["list-panes", "-F", PANE_FORMAT, "-t", session])
.output()
.with_context(|| format!("Failed to list panes for session '{}'", session))?;
if output.status.success() {
let panes_str = String::from_utf8_lossy(&output.stdout);
match parse_panes_list(&panes_str) {
Ok(panes) if !panes.is_empty() => return Ok(panes),
Ok(_) => {
}
Err(e) => {
if attempt == max_retries - 1 {
return Err(e);
}
}
}
} else if attempt == max_retries - 1 {
return Err(SpriteError::tmux_with_source(
format!("Failed to list panes for session '{}'", session),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let delay = std::time::Duration::from_millis(100 * (1 << attempt)); std::thread::sleep(delay);
}
Ok(Vec::new())
}
#[derive(Debug, Clone)]
pub struct PaneInfo {
pub index: usize,
pub pane_id: String,
pub current_path: Option<String>,
pub current_command: Option<String>,
}
fn parse_panes_list(output: &str) -> Result<Vec<PaneInfo>> {
let mut panes = Vec::new();
for line in output.lines() {
if line.trim().is_empty() {
continue;
}
let parts: Vec<&str> = line.splitn(4, '|').collect();
if parts.len() < 2 {
continue;
}
let index = parts[0].trim().parse::<usize>().unwrap_or(0);
let pane_id = parts[1].trim().to_string();
let current_path = parts
.get(2)
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.map(|p| p.to_string());
let current_command = parts
.get(3)
.map(|c| c.trim())
.filter(|c| !c.is_empty())
.map(|c| c.to_string());
panes.push(PaneInfo {
index,
pane_id,
current_path,
current_command,
});
}
Ok(panes)
}
#[allow(dead_code)]
pub fn select_pane(session: &str, pane_index: usize) -> Result<()> {
let target_spec = build_target_spec(session, &pane_index.to_string());
let output = Command::new("tmux")
.args(["select-pane", "-t", &target_spec])
.output()
.with_context(|| {
format!(
"Failed to select pane {} in session '{}'",
pane_index, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to select pane {} in session '{}'",
pane_index, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn get_pane_cwd(session: &str, pane_index: usize) -> Result<String> {
let target_spec = build_target_spec(session, &pane_index.to_string());
let output = Command::new("tmux")
.args([
"display-message",
"-p",
"-t",
&target_spec,
"#{pane_current_path}",
])
.output()
.with_context(|| {
format!(
"Failed to get current path for pane {} in session '{}'",
pane_index, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to get current path for pane {} in session '{}'",
pane_index, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
pub fn get_pane_current_path(session: &str, pane_id: &str) -> Result<String> {
let target_spec = build_target_spec(session, pane_id);
let output = Command::new("tmux")
.args([
"display-message",
"-p",
"-t",
&target_spec,
"#{pane_current_path}",
])
.output()
.with_context(|| {
format!(
"Failed to get current path for pane '{}' in session '{}'",
pane_id, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to get current path for pane '{}' in session '{}'",
pane_id, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
pub fn send_keys_with_delay(
session: &str,
target: &str,
command: &str,
delay_ms: u64,
) -> Result<()> {
let target_spec = build_target_spec(session, target);
let output = Command::new("tmux")
.args(["send-keys", "-t", &target_spec, command, "C-m"])
.output()
.with_context(|| {
format!(
"Failed to send keys to pane '{}' in session '{}'",
target, session
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to send keys to pane '{}' in session '{}'",
target, session
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
if delay_ms > 0 {
std::thread::sleep(std::time::Duration::from_millis(delay_ms));
}
Ok(())
}
#[allow(dead_code)]
pub fn create_window_with_path(
session: &str,
window_name: &str,
working_dir: &str,
) -> Result<String> {
let output = Command::new("tmux")
.args([
"new-window",
"-t",
session,
"-n",
window_name,
"-c",
working_dir,
])
.output()
.with_context(|| {
format!(
"Failed to create window '{}' in session '{}' with path '{}'",
window_name, session, working_dir
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to create window '{}' in session '{}' with path '{}'",
window_name, session, working_dir
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let window_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(window_id)
}
#[allow(dead_code)]
pub fn rename_window(session: &str, window_index: &str, new_name: &str) -> Result<()> {
let output = Command::new("tmux")
.args([
"rename-window",
"-t",
&format!("{}.{}", session, window_index),
new_name,
])
.output()
.with_context(|| {
format!(
"Failed to rename window '{}.{}' to '{}'",
session, window_index, new_name
)
})?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!(
"Failed to rename window '{}.{}' to '{}'",
session, window_index, new_name
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn send_command_to_pane(session: &str, pane: &str, command: &str) -> Result<()> {
send_keys(session, pane, command)
}
#[allow(dead_code)]
pub fn focus_pane(session: &str, pane: &str) -> Result<()> {
let output = Command::new("tmux")
.args(["select-pane", "-t", &format!("{}.{}", session, pane)])
.output()
.with_context(|| format!("Failed to focus pane '{}' in session '{}'", pane, session))?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!("Failed to focus pane '{}' in session '{}'", pane, session),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn zoom_pane(session: &str, pane: &str) -> Result<()> {
let target_spec = build_target_spec(session, pane);
let output = Command::new("tmux")
.args(["resize-pane", "-Z", "-t", &target_spec])
.output()
.with_context(|| format!("Failed to zoom pane '{}' in session '{}'", pane, session))?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!("Failed to zoom pane '{}' in session '{}'", pane, session),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
pub fn list_panes(session: &str) -> Result<Vec<PaneDetails>> {
let output = Command::new("tmux")
.args(["list-panes", "-a", "-t", session])
.output()
.with_context(|| format!("Failed to list panes for session '{}'", session))?;
if !output.status.success() {
return Err(SpriteError::tmux_with_source(
format!("Failed to list panes for session '{}'", session),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let panes_str = String::from_utf8_lossy(&output.stdout);
parse_panes_details(&panes_str)
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct PaneDetails {
pub id: String,
pub session: String,
pub window: usize,
pub pane: usize,
pub current_path: Option<String>,
pub current_command: Option<String>,
pub title: Option<String>,
pub active: bool,
}
fn parse_panes_details(output: &str) -> Result<Vec<PaneDetails>> {
let mut panes = Vec::new();
for line in output.lines() {
if line.trim().is_empty() {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.is_empty() {
continue;
}
let pane_id = parts[0];
let id_parts: Vec<&str> = pane_id.split(':').collect();
if id_parts.len() != 2 {
continue;
}
let session = id_parts[0].to_string();
let window_pane = id_parts[1];
let wp_parts: Vec<&str> = window_pane.split('.').collect();
if wp_parts.len() != 2 {
continue;
}
let window = wp_parts[0].parse::<usize>().unwrap_or(0);
let pane = wp_parts[1].parse::<usize>().unwrap_or(0);
let current_command = parts
.iter()
.find(|part| part.starts_with('[') && part.ends_with(']'))
.map(|cmd| {
cmd.trim_start_matches('[')
.trim_end_matches(']')
.to_string()
});
panes.push(PaneDetails {
id: pane_id.to_string(),
session,
window,
pane,
current_path: None, current_command,
title: None, active: false, });
}
Ok(panes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_sessions_list() {
let input = r#"
sprite-session: 3 windows (created Wed Oct 18 10:30:00 2023) [attached]
another-session: 1 windows (created Wed Oct 18 09:15:00 2023)
"#;
let sessions = parse_sessions_list(input).unwrap();
assert_eq!(sessions.len(), 2);
assert_eq!(sessions[0].name, "sprite-session");
assert_eq!(sessions[0].windows, 3);
assert!(sessions[0].attached);
assert_eq!(sessions[1].name, "another-session");
assert_eq!(sessions[1].windows, 1);
assert!(!sessions[1].attached);
}
#[test]
fn test_is_tmux_available() {
let _result = is_tmux_available();
}
}