use crate::error::SpriteError;
use crate::utils::project;
use crate::utils::tmux;
use anyhow::{Context, Result};
pub fn execute(session_name: Option<String>, list: bool) -> Result<()> {
if list {
return project::execute_from_project_root(list_sessions_from_project_root);
}
attach_with_project_root_detection(session_name)
}
fn list_sessions_from_project_root() -> Result<()> {
tmux::is_tmux_available()
.context("tmux is not available. Please install tmux to use sprite attach.")?;
list_available_sessions()
}
fn attach_with_project_root_detection(session_name: Option<String>) -> Result<()> {
tmux::is_tmux_available()
.context("tmux is not available. Please install tmux to use sprite attach.")?;
let original_dir = std::env::current_dir().context("Failed to get current directory")?;
let _project_root = project::find_project_root()?;
project::change_to_project_root()?;
let session_name = match session_name {
Some(name) => name,
None => {
find_default_session()?
}
};
if !tmux::session_exists(&session_name)? {
return Err(SpriteError::session(
format!(
"Session '{}' does not exist. Use --list to see available sessions.",
session_name
),
Some(session_name.clone()),
)
.into());
}
let sessions = tmux::list_sessions().context("Failed to list sessions")?;
let session_info = sessions
.iter()
.find(|s| s.name == session_name)
.ok_or_else(|| {
SpriteError::session(
format!("Session '{}' not found in session list", session_name),
Some(session_name.clone()),
)
})?;
println!("đ Attaching to tmux session: {}", session_name);
if session_info.attached {
println!("âšī¸ Session is already attached by another client");
}
println!("đĄ Use 'Ctrl+B D' to detach from the session");
println!("đĄ You'll return to directory: {}", original_dir.display());
println!();
let _ = project::restore_original_directory(&original_dir);
tmux::attach_session(&session_name)
.with_context(|| format!("Failed to attach to session '{}'", session_name))?;
println!("đ Detached from session '{}'", session_name);
Ok(())
}
fn find_default_session() -> Result<String> {
let sessions = tmux::list_sessions().context("Failed to list sessions")?;
if let Some(session) = sessions.iter().find(|s| s.name.contains("sprite-session")) {
return Ok(session.name.clone());
}
if let Some(session) = sessions.first() {
return Ok(session.name.clone());
}
Err(SpriteError::session(
"No tmux sessions found. Use 'sprite start' to create a new session.",
None::<String>,
)
.into())
}
fn list_available_sessions() -> Result<()> {
let sessions = match tmux::list_sessions() {
Ok(s) => s,
Err(_) => {
println!("đ No tmux sessions found.");
println!(" Use 'sprite start' to create a new multi-agent session.");
return Ok(());
}
};
if sessions.is_empty() {
println!("đ No tmux sessions found.");
println!(" Use 'sprite start' to create a new multi-agent session.");
return Ok(());
}
println!("đ Available tmux sessions:");
println!();
for session in sessions {
let status = if session.attached {
"đĸ Active".to_string()
} else {
"âĒ Detached".to_string()
};
let created_ago = format_time_ago(&session.created);
println!(
" {} {} ({} windows) - {}",
status, session.name, session.windows, created_ago
);
}
println!();
println!("đĄ Use 'sprite attach <session-name>' to connect to a session");
Ok(())
}
fn format_time_ago(timestamp: &str) -> String {
format!("created {}", timestamp)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_time_ago() {
let sample_timestamp = "2025-01-01T12:00:00";
let result = format_time_ago(sample_timestamp);
assert!(result.contains("created"));
assert!(result.contains(sample_timestamp));
}
#[test]
fn test_format_time_ago_empty() {
let empty_timestamp = "";
let result = format_time_ago(empty_timestamp);
assert!(result.contains("created"));
}
#[test]
fn test_find_default_session_empty_list() {
}
}