tmux-tango 2.10.0

A CLI tool for managing tmux sessions - dance between your sessions!
Documentation
//! Background polling of remote hosts.
//!
//! Each configured host gets its own thread that probes the machine once (where are `tmux`
//! and `tango`?), then lists sessions and windows on a slow cadence and ships snapshots to
//! the TUI over a channel. The TUI thread never touches ssh, so a dead or slow host costs it
//! nothing but a stale node. Failures back off exponentially so an unreachable host is not
//! hammered every few seconds for the life of the process.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::error::TmuxFzfError;
use crate::host::Host;
use crate::tmux::{TmuxClient, TmuxSession, TmuxWindow};

/// Poll cadence while a host is healthy.
pub const BASE_INTERVAL: Duration = Duration::from_secs(5);
/// Cap on the backoff while a host is failing.
pub const MAX_INTERVAL: Duration = Duration::from_secs(60);
/// Granularity at which a sleeping poller notices a stop request.
const STOP_CHECK: Duration = Duration::from_millis(250);

/// Shell snippet that reports where `tmux` and a usable `tango` live. The `tango attach --help`
/// check doubles as a version gate: a tango too old to have `attach` is reported as absent so
/// the attach degrades to plain tmux instead of failing on the remote.
const PROBE_SCRIPT: &str = "printf \"tmux=%s\\n\" \"$(command -v tmux)\"; \
     printf \"tango=%s\\n\" \"$(tango attach --help >/dev/null 2>&1 && command -v tango)\"";

/// Re-run the probe under the user's *login* shell so PATH additions from `.zprofile` /
/// `.bash_profile` (Homebrew, `~/.cargo/bin`) are visible. `sh -c '<wrapper>' '<script>'`
/// passes the script as `$0`, which sidesteps a second layer of quoting.
const LOGIN_SHELL_WRAPPER: &str = "exec \"${SHELL:-/bin/sh}\" -l -c \"$0\"";

#[derive(Debug, Clone, PartialEq)]
pub enum HostState {
    /// No poll has completed yet.
    Loading,
    Online {
        sessions: Vec<TmuxSession>,
        /// Windows keyed by session name, from one `list-windows -a` call.
        windows: HashMap<Arc<str>, Vec<TmuxWindow>>,
        /// Absolute path of the remote tmux binary.
        tmux_path: String,
        /// Absolute path of a remote tango with `attach`, if any.
        tango_path: Option<String>,
    },
    /// ssh could not reach the host, or tmux failed there.
    Offline { error: String },
    /// ssh works but there is no tmux on the host.
    NoTmux,
}

#[derive(Debug)]
pub struct HostUpdate {
    pub alias: Arc<str>,
    pub state: HostState,
}

/// Owner handle for a poller thread. The thread exits at its next stop check; it is never
/// joined, because a poller blocked in a 5 s ssh connect must not delay TUI shutdown.
pub struct PollerHandle {
    stop: Arc<AtomicBool>,
}

impl PollerHandle {
    pub fn stop(&self) {
        self.stop.store(true, Ordering::Relaxed);
    }
}

impl Drop for PollerHandle {
    fn drop(&mut self) {
        self.stop();
    }
}

/// What the probe found on a host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Probe {
    pub tmux_path: Option<String>,
    pub tango_path: Option<String>,
}

/// Outcome of one probe command, before the login-shell retry is considered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeOutcome {
    /// ssh itself failed (exit 255, killed, or could not spawn).
    Unreachable(String),
    /// ssh ran the script; here is what it reported.
    Ran(Probe),
}

/// Parse the probe script's stdout (`tmux=…` / `tango=…` lines). Empty values are absent.
pub fn parse_probe_output(stdout: &str) -> Probe {
    let mut probe = Probe { tmux_path: None, tango_path: None };
    for line in stdout.lines() {
        let Some((key, value)) = line.split_once('=') else { continue };
        let value = value.trim();
        let slot = match key.trim() {
            "tmux" => &mut probe.tmux_path,
            "tango" => &mut probe.tango_path,
            _ => continue,
        };
        if !value.is_empty() {
            *slot = Some(value.to_string());
        }
    }
    probe
}

/// Interpret an ssh exit status plus captured output. ssh reserves exit 255 for its own
/// failures; anything else is the remote command's status, and the script always exits 0.
pub fn classify_probe(exit_code: Option<i32>, stdout: &str, stderr: &str) -> ProbeOutcome {
    match exit_code {
        Some(255) | None => ProbeOutcome::Unreachable(summarize_error(stderr)),
        Some(_) => ProbeOutcome::Ran(parse_probe_output(stdout)),
    }
}

/// Reduce an error blob to the single line a tree node can show: the first non-empty line,
/// starting at `ssh:` when ssh is the one complaining, since the tmux prefixes our client
/// wraps around it add nothing on a remote host.
pub fn summarize_error(text: &str) -> String {
    let line = text
        .lines()
        .map(str::trim)
        .find(|l| !l.is_empty())
        .unwrap_or("unknown error");
    let line = line.find("ssh: ").map(|i| &line[i..]).unwrap_or(line);
    line.to_string()
}

/// 5 s while healthy; on failure double the current wait up to 60 s.
pub fn next_interval(current: Duration, ok: bool) -> Duration {
    if ok {
        BASE_INTERVAL
    } else {
        (current * 2).min(MAX_INTERVAL)
    }
}

/// Start polling `alias` on its own thread. Updates arrive on `tx`; the thread exits when the
/// handle is stopped/dropped or the receiver is gone.
pub fn spawn_poller(alias: Arc<str>, tx: Sender<HostUpdate>) -> PollerHandle {
    let stop = Arc::new(AtomicBool::new(false));
    let thread_stop = Arc::clone(&stop);
    let thread_name = format!("tango-poll-{}", alias);
    let spawned = thread::Builder::new()
        .name(thread_name)
        .spawn(move || poll_loop(alias, tx, thread_stop));
    if spawned.is_err() {
        // Out of threads: leave the host in Loading forever rather than crash the TUI.
        stop.store(true, Ordering::Relaxed);
    }
    PollerHandle { stop }
}

fn poll_loop(alias: Arc<str>, tx: Sender<HostUpdate>, stop: Arc<AtomicBool>) {
    let host = Host::remote(&alias);
    let mut interval = BASE_INTERVAL;
    let mut probe: Option<Probe> = None;

    while !stop.load(Ordering::Relaxed) {
        let state = poll_once(&host, &mut probe);
        let ok = matches!(state, HostState::Online { .. });
        if !ok {
            // Paths may differ after a reinstall or reboot; re-probe once the host is back.
            probe = None;
        }
        if tx.send(HostUpdate { alias: Arc::clone(&alias), state }).is_err() {
            return;
        }
        interval = next_interval(interval, ok);
        sleep_until_stopped(interval, &stop);
    }
}

/// One full poll: probe if needed, then list sessions and windows.
fn poll_once(host: &Host, probe: &mut Option<Probe>) -> HostState {
    if probe.is_none() {
        match run_probe(host) {
            Ok(found) => *probe = Some(found),
            Err(state) => return state,
        }
    }
    let Some(tmux_path) = probe.as_ref().and_then(|p| p.tmux_path.clone()) else {
        return HostState::NoTmux;
    };
    let tango_path = probe.as_ref().and_then(|p| p.tango_path.clone());

    let mut client = TmuxClient::for_host(host.clone()).with_program(&tmux_path);
    let sessions = match client.list_sessions() {
        Ok(sessions) => sessions,
        Err(TmuxFzfError::NoSessions) => Vec::new(),
        Err(e) => return HostState::Offline { error: summarize_error(&e.to_string()) },
    };

    // Best effort: a window listing failure should not hide the sessions we already have.
    let mut windows: HashMap<Arc<str>, Vec<TmuxWindow>> = HashMap::new();
    if !sessions.is_empty() {
        if let Ok(pairs) = client.list_all_windows() {
            for (session, window) in pairs {
                windows.entry(session).or_default().push(window);
            }
        }
    }

    HostState::Online { sessions, windows, tmux_path, tango_path }
}

/// Probe under a plain `sh`, then under the login shell if tmux was not found the first time.
fn run_probe(host: &Host) -> Result<Probe, HostState> {
    let first = execute_probe(host, &["-c", PROBE_SCRIPT])?;
    if first.tmux_path.is_some() {
        return Ok(first);
    }
    let retry = execute_probe(host, &["-c", LOGIN_SHELL_WRAPPER, PROBE_SCRIPT])?;
    if retry.tmux_path.is_some() {
        Ok(retry)
    } else {
        Err(HostState::NoTmux)
    }
}

fn execute_probe(host: &Host, sh_args: &[&str]) -> Result<Probe, HostState> {
    let output = host
        .command("sh", sh_args, false)
        .stdin(std::process::Stdio::null())
        .output()
        .map_err(|e| HostState::Offline { error: format!("cannot run ssh: {}", e) })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    match classify_probe(output.status.code(), &stdout, &stderr) {
        ProbeOutcome::Unreachable(error) => Err(HostState::Offline { error }),
        ProbeOutcome::Ran(probe) => Ok(probe),
    }
}

fn sleep_until_stopped(total: Duration, stop: &AtomicBool) {
    let mut slept = Duration::ZERO;
    while slept < total && !stop.load(Ordering::Relaxed) {
        let step = STOP_CHECK.min(total - slept);
        thread::sleep(step);
        slept += step;
    }
}

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

    #[test]
    fn next_interval_doubles_on_failure_and_caps_at_max() {
        let mut d = BASE_INTERVAL;
        let mut seen = Vec::new();
        for _ in 0..6 {
            d = next_interval(d, false);
            seen.push(d.as_secs());
        }
        assert_eq!(seen, vec![10, 20, 40, 60, 60, 60]);
    }

    #[test]
    fn next_interval_resets_to_base_on_success() {
        assert_eq!(next_interval(MAX_INTERVAL, true), BASE_INTERVAL);
        assert_eq!(next_interval(BASE_INTERVAL, true), BASE_INTERVAL);
    }

    #[test]
    fn parse_probe_output_reads_both_paths() {
        let probe = parse_probe_output("tmux=/usr/bin/tmux\ntango=/home/k/.cargo/bin/tango\n");
        assert_eq!(probe.tmux_path.as_deref(), Some("/usr/bin/tmux"));
        assert_eq!(probe.tango_path.as_deref(), Some("/home/k/.cargo/bin/tango"));
    }

    #[test]
    fn parse_probe_output_treats_empty_value_as_absent() {
        let probe = parse_probe_output("tmux=/usr/bin/tmux\ntango=\n");
        assert_eq!(probe.tmux_path.as_deref(), Some("/usr/bin/tmux"));
        assert_eq!(probe.tango_path, None);
    }

    #[test]
    fn parse_probe_output_with_nothing_found() {
        let probe = parse_probe_output("tmux=\ntango=\n");
        assert_eq!(probe, Probe { tmux_path: None, tango_path: None });
    }

    #[test]
    fn parse_probe_output_ignores_login_banner_noise() {
        // A chatty .profile may print before our lines; only key=value lines count.
        let probe = parse_probe_output("Welcome to box\ntmux=/opt/homebrew/bin/tmux\nfoo=bar\n");
        assert_eq!(probe.tmux_path.as_deref(), Some("/opt/homebrew/bin/tmux"));
        assert_eq!(probe.tango_path, None);
    }

    #[test]
    fn classify_probe_exit_255_is_unreachable_with_ssh_message() {
        let outcome = classify_probe(
            Some(255),
            "",
            "ssh: connect to host box port 22: Connection refused\r\n",
        );
        assert_eq!(
            outcome,
            ProbeOutcome::Unreachable("ssh: connect to host box port 22: Connection refused".into())
        );
    }

    #[test]
    fn classify_probe_signal_death_is_unreachable() {
        assert!(matches!(classify_probe(None, "", ""), ProbeOutcome::Unreachable(_)));
    }

    #[test]
    fn classify_probe_exit_zero_parses_stdout() {
        let outcome = classify_probe(Some(0), "tmux=/usr/bin/tmux\ntango=\n", "");
        assert_eq!(
            outcome,
            ProbeOutcome::Ran(Probe { tmux_path: Some("/usr/bin/tmux".into()), tango_path: None })
        );
    }

    #[test]
    fn summarize_error_takes_first_nonempty_line_from_ssh() {
        let text = "tmux error: tmux list-sessions failed: ssh: Could not resolve hostname box: nodename nor servname provided\nsecond line";
        assert_eq!(
            summarize_error(text),
            "ssh: Could not resolve hostname box: nodename nor servname provided"
        );
    }

    #[test]
    fn summarize_error_keeps_non_ssh_lines_and_handles_empty() {
        assert_eq!(summarize_error("\n  server exited unexpectedly  \n"), "server exited unexpectedly");
        assert_eq!(summarize_error(""), "unknown error");
    }

    #[test]
    fn poller_handle_stop_flag_is_observed() {
        let stop = Arc::new(AtomicBool::new(false));
        let handle = PollerHandle { stop: Arc::clone(&stop) };
        let started = std::time::Instant::now();
        let sleeper = {
            let stop = Arc::clone(&stop);
            thread::spawn(move || sleep_until_stopped(Duration::from_secs(30), &stop))
        };
        drop(handle);
        sleeper.join().unwrap();
        assert!(started.elapsed() < Duration::from_secs(5), "drop must wake the sleeper promptly");
    }

    #[test]
    fn probe_script_is_single_quote_free() {
        // The script travels inside one single-quoted ssh argument and then inside
        // `sh -c '...'`; a stray `'` would break both layers.
        assert!(!PROBE_SCRIPT.contains('\''), "{}", PROBE_SCRIPT);
        assert!(!LOGIN_SHELL_WRAPPER.contains('\''), "{}", LOGIN_SHELL_WRAPPER);
    }
}