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};
pub const BASE_INTERVAL: Duration = Duration::from_secs(5);
pub const MAX_INTERVAL: Duration = Duration::from_secs(60);
const STOP_CHECK: Duration = Duration::from_millis(250);
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)\"";
const LOGIN_SHELL_WRAPPER: &str = "exec \"${SHELL:-/bin/sh}\" -l -c \"$0\"";
#[derive(Debug, Clone, PartialEq)]
pub enum HostState {
Loading,
Online {
sessions: Vec<TmuxSession>,
windows: HashMap<Arc<str>, Vec<TmuxWindow>>,
tmux_path: String,
tango_path: Option<String>,
},
Offline { error: String },
NoTmux,
}
#[derive(Debug)]
pub struct HostUpdate {
pub alias: Arc<str>,
pub state: HostState,
}
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();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Probe {
pub tmux_path: Option<String>,
pub tango_path: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeOutcome {
Unreachable(String),
Ran(Probe),
}
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
}
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)),
}
}
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()
}
pub fn next_interval(current: Duration, ok: bool) -> Duration {
if ok {
BASE_INTERVAL
} else {
(current * 2).min(MAX_INTERVAL)
}
}
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() {
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 {
probe = None;
}
if tx.send(HostUpdate { alias: Arc::clone(&alias), state }).is_err() {
return;
}
interval = next_interval(interval, ok);
sleep_until_stopped(interval, &stop);
}
}
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()) },
};
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 }
}
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() {
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() {
assert!(!PROBE_SCRIPT.contains('\''), "{}", PROBE_SCRIPT);
assert!(!LOGIN_SHELL_WRAPPER.contains('\''), "{}", LOGIN_SHELL_WRAPPER);
}
}