tmux-tango 2.13.0

A CLI tool for managing tmux sessions - dance between your sessions!
Documentation
//! The managed attach ceremony shared by the TUI and the `tango attach` subcommand.
//!
//! "Managed" means the attach carries everything tango layers on top of a bare
//! `tmux attach-session`: a grouped viewer session when another client already holds the
//! target (so two terminals don't mirror), and the per-session `@tango_active` flag that arms
//! the Alt-Left detach binding. Keeping it in one function is what lets a *remote* tango
//! (`ssh -t host tango attach <s>`) behave exactly like a local TUI attach.

use crate::error::TmuxFzfError;
use crate::tmux::{viewer_session_name, TmuxClient};
use crate::tmux_bindings;

/// Split a `tango attach` argument into `(session, window)`.
///
/// tmux forbids `:` in session names, so the first `:` is unambiguously the window separator.
/// A non-numeric suffix is an error rather than a session named `dev:x`, which tmux could not
/// create anyway.
pub fn parse_attach_target(arg: &str) -> Result<(String, Option<u32>), TmuxFzfError> {
    match arg.split_once(':') {
        None => Ok((arg.to_string(), None)),
        Some((session, window)) => {
            let window = window.parse().map_err(|_| {
                TmuxFzfError::InvalidSessionName(format!(
                    "'{}' is not a window index in '{}'", window, arg
                ))
            })?;
            Ok((session.to_string(), Some(window)))
        }
    }
}

/// Attach to `session` (optionally a specific window/pane) with viewer grouping and the
/// Alt-Left binding armed. Blocks until the client detaches, then tears both down.
///
/// Must only be called on a *local* client: `install_binding`/`set_active` talk to the local
/// tmux server, and grouping needs `process_alive` on the local host.
pub fn attach_managed(
    client: &mut TmuxClient,
    session: &str,
    window: Option<u32>,
    pane: Option<u32>,
) -> Result<(), TmuxFzfError> {
    // When another client already holds the source session, attach through a hidden grouped
    // viewer so each terminal keeps its own current window — tmux mirrors all clients of one
    // session. Grouping is impossible in the inside-tmux switch-client branch: switch-client
    // returns immediately, so the viewer's lifecycle would have no owner.
    let viewer = if !client.is_inside_tmux()
        && client.session_attached_count(session).unwrap_or(0) > 0
    {
        let name = viewer_session_name(session, std::process::id());
        // A crashed run's viewer may still hold this name after pid reuse.
        let _ = client.kill_session(&name);
        client.create_grouped_session(session, &name).ok()
    } else {
        None
    };
    let attach_session = viewer.as_deref().unwrap_or(session);

    // Re-installed here (not only in BindingGuard::new) because no server may have existed
    // when the guard was constructed.
    tmux_bindings::install_binding();
    tmux_bindings::set_active(attach_session);

    let result = match (window, pane) {
        (None, _) => client.attach_session(attach_session),
        (Some(w), None) => client.attach_window(attach_session, w),
        (Some(w), Some(p)) => client.attach_pane(attach_session, w, p),
    };

    tmux_bindings::clear_active(attach_session);
    if let Some(viewer_name) = &viewer {
        let _ = client.kill_session(viewer_name);
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_attach_target_session_only() {
        assert_eq!(parse_attach_target("dev").unwrap(), ("dev".to_string(), None));
    }

    #[test]
    fn parse_attach_target_session_and_window() {
        assert_eq!(parse_attach_target("dev:3").unwrap(), ("dev".to_string(), Some(3)));
    }

    #[test]
    fn parse_attach_target_keeps_dashes_in_session_name() {
        assert_eq!(
            parse_attach_target("my-agent-1:0").unwrap(),
            ("my-agent-1".to_string(), Some(0))
        );
    }

    #[test]
    fn parse_attach_target_rejects_non_numeric_window() {
        let err = parse_attach_target("dev:x").unwrap_err();
        assert!(
            matches!(err, TmuxFzfError::InvalidSessionName(_)),
            "expected InvalidSessionName, got {:?}", err
        );
    }

    #[test]
    fn parse_attach_target_rejects_empty_window() {
        assert!(parse_attach_target("dev:").is_err(), "trailing ':' has no window index");
    }
}