tmux-tango 2.13.0

A CLI tool for managing tmux sessions - dance between your sessions!
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! 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::{self, Receiver, 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 {
    pub alias: Arc<str>,
    stop: Arc<AtomicBool>,
    wake: Arc<AtomicBool>,
}

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

    /// Cut the current sleep short and drop the failure backoff, so a host the user just
    /// reconnected is re-polled now rather than up to `MAX_INTERVAL` later.
    pub fn wake(&self) {
        self.wake.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 wake = Arc::new(AtomicBool::new(false));
    let (thread_stop, thread_wake) = (Arc::clone(&stop), Arc::clone(&wake));
    let thread_alias = Arc::clone(&alias);
    let thread_name = format!("tango-poll-{}", alias);
    let spawned = thread::Builder::new()
        .name(thread_name)
        .spawn(move || poll_loop(thread_alias, tx, thread_stop, thread_wake));
    if spawned.is_err() {
        // Out of threads: leave the host in Loading forever rather than crash the TUI.
        stop.store(true, Ordering::Relaxed);
    }
    PollerHandle { alias, stop, wake }
}

fn poll_loop(alias: Arc<str>, tx: Sender<HostUpdate>, stop: Arc<AtomicBool>, wake: 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);
        if sleep_until_stopped(interval, &stop, &wake) {
            interval = BASE_INTERVAL;
        }
    }
}

/// 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),
    }
}

/// Sleep `total`, ending early on a stop or a wake. Returns whether a wake ended it, and
/// clears the flag so the next sleep is a full one.
fn sleep_until_stopped(total: Duration, stop: &AtomicBool, wake: &AtomicBool) -> bool {
    let mut slept = Duration::ZERO;
    while slept < total && !stop.load(Ordering::Relaxed) {
        if wake.swap(false, Ordering::Relaxed) {
            return true;
        }
        let step = STOP_CHECK.min(total - slept);
        thread::sleep(step);
        slept += step;
    }
    wake.swap(false, Ordering::Relaxed)
}

/// Which remote pane a preview shows: `"<session>:"` (the session's current window) or
/// `"<session>:<index>"`, on the host `host`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreviewKey {
    pub host: Arc<str>,
    pub target: String,
}

#[derive(Debug, Clone)]
pub struct PreviewRequest {
    pub key: PreviewKey,
    /// Absolute path of the remote tmux, from the host's `Online` snapshot.
    pub tmux_path: String,
}

#[derive(Debug)]
pub struct PreviewResult {
    pub key: PreviewKey,
    /// Pane content with escape sequences, or a one-line error.
    pub content: Result<String, String>,
}

/// Start a capture worker for `alias`; send it requests on the returned `Sender`. The thread
/// exits once that sender is dropped (after any in-flight ssh returns); it is never joined.
pub fn spawn_previewer(alias: Arc<str>, results: Sender<PreviewResult>) -> Sender<PreviewRequest> {
    let (tx, rx) = mpsc::channel();
    let host = Host::remote(&alias);
    let capture = move |req: &PreviewRequest| {
        TmuxClient::for_host(host.clone())
            .with_program(&req.tmux_path)
            .capture_pane(&req.key.target)
            .map_err(|e| summarize_error(&e.to_string()))
    };
    // Out of threads: the request sender just goes nowhere and the preview stays "loading".
    let _ = thread::Builder::new()
        .name(format!("tango-preview-{}", alias))
        .spawn(move || preview_loop(rx, results, capture));
    tx
}

/// Serve capture requests, newest first: everything queued behind the next request is
/// skipped, so a cursor sweeping across many remote rows costs one capture, not one per row.
fn preview_loop(
    rx: Receiver<PreviewRequest>,
    tx: Sender<PreviewResult>,
    capture: impl Fn(&PreviewRequest) -> Result<String, String>,
) {
    while let Ok(mut req) = rx.recv() {
        while let Ok(newer) = rx.try_recv() {
            req = newer;
        }
        let content = capture(&req);
        if tx.send(PreviewResult { key: req.key, content }).is_err() {
            return;
        }
    }
}

#[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");
    }

    fn handle() -> PollerHandle {
        PollerHandle {
            alias: "box".into(),
            stop: Arc::new(AtomicBool::new(false)),
            wake: Arc::new(AtomicBool::new(false)),
        }
    }

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

    #[test]
    fn wake_cuts_a_backoff_sleep_short_exactly_once() {
        let handle = handle();
        let (stop, wake) = (Arc::clone(&handle.stop), Arc::clone(&handle.wake));
        let started = std::time::Instant::now();
        let sleeper = thread::spawn(move || {
            let first = sleep_until_stopped(MAX_INTERVAL, &stop, &wake);
            let after_first = started.elapsed();
            // A flag left set would turn every later sleep into a 250 ms spin against ssh.
            let second = sleep_until_stopped(Duration::from_millis(600), &stop, &wake);
            (first, after_first, second, started.elapsed())
        });
        thread::sleep(Duration::from_millis(100));
        handle.wake();
        let (first, after_first, second, total) = sleeper.join().unwrap();
        assert!(first, "wake must report itself so poll_loop resets the backoff");
        assert!(after_first < Duration::from_secs(2), "woke after {:?}", after_first);
        assert!(!second, "the wake flag must be consumed by the first sleep");
        assert!(total - after_first >= Duration::from_millis(600), "second sleep cut short: {:?}", total - after_first);
    }

    #[test]
    fn preview_loop_skips_requests_superseded_while_a_capture_runs() {
        let request = |target: &str| PreviewRequest {
            key: PreviewKey { host: "box".into(), target: target.to_string() },
            tmux_path: "/usr/bin/tmux".to_string(),
        };
        let (req_tx, req_rx) = mpsc::channel();
        let (res_tx, res_rx) = mpsc::channel();
        let (started_tx, started_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel::<()>();
        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));

        let worker = {
            let captured = Arc::clone(&captured);
            thread::spawn(move || {
                preview_loop(req_rx, res_tx, |req| {
                    captured.lock().unwrap().push(req.key.target.clone());
                    if req.key.target == "a:" {
                        // Stand in for a slow ssh round trip on the first capture.
                        started_tx.send(()).unwrap();
                        release_rx.recv().unwrap();
                    }
                    Ok(format!("content of {}", req.key.target))
                })
            })
        };

        req_tx.send(request("a:")).unwrap();
        started_rx.recv().unwrap();
        for target in ["b:", "c:1", "d:"] {
            req_tx.send(request(target)).unwrap();
        }
        release_tx.send(()).unwrap();
        drop(req_tx);
        worker.join().unwrap();

        let captured = captured.lock().unwrap().clone();
        assert_eq!(captured, vec!["a:", "d:"], "only the newest queued request should be captured");
        let results: Vec<(String, Result<String, String>)> =
            res_rx.try_iter().map(|r| (r.key.target, r.content)).collect();
        assert_eq!(
            results,
            vec![
                ("a:".to_string(), Ok("content of a:".to_string())),
                ("d:".to_string(), Ok("content of d:".to_string())),
            ],
            "each capture must report back under its own key"
        );
    }

    #[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);
    }
}