Skip to main content

taimux_cli/
remote.rs

1//! Other hosts' sessions, in the same list.
2//!
3//! A pane holding `ssh <host> -t tmux …` is a window onto a whole other tmux
4//! server, and the agents running in it are invisible to
5//! everything else here: they are not this server's panes and not this box's
6//! processes. But that host has a taimux of its own, and `list` is a complete
7//! answer about it.
8//!
9//! **The rule that makes this safe is: federate, never reach in.** Each host is
10//! asked about ITSELF, so the hook state, the screen reading, the versions and
11//! the transcripts all stay on the side that can see them, and `list` is
12//! deliberately local-only because it is the wire format. That one rule is what
13//! makes a cycle between two boxes ssh'd into each other structurally impossible
14//! rather than merely unlikely.
15//!
16//! **Hosts are DISCOVERED, not configured**: whatever the local panes are already
17//! ssh'd into is the list. That is not just less setup. A host found this way has
18//! a warm ssh ControlMaster by construction (the pane's own connection), so a
19//! fetch is a tenth of a second rather than a handshake; it drops off the list
20//! when its pane goes; and it arrives with its jump target already identified,
21//! since the pane it was found in IS the way back to it.
22//!
23//! Nothing on the refresh path waits on the network except a host with NOTHING
24//! cached, which is fetched once per boot so the first picker after a reboot is
25//! complete. Everything else is served as it stands and refreshed behind the
26//! picker.
27
28use std::io::Read;
29use std::path::{Path, PathBuf};
30use std::process::{Command, Stdio};
31use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
32
33use taimux_core::{env, index, proc};
34
35/// Rebuilding PATH on the far side, because `taimux` is NOT on a
36/// non-interactive ssh's PATH on a stock install: `~/.local/bin` is
37/// login-shell-only, so `ssh ha taimux list` fails where
38/// `ssh ha '~/.local/bin/taimux list'` works. It also covers a host that has
39/// taimux only as a tmux plugin, and it exits 127 when there is none, which is
40/// how "no taimux over there" is told apart from "unreachable".
41const REMOTE_TAIMUX: &str = "PATH=\"$HOME/.local/bin:$HOME/bin:$PATH\"; \
42     for d in \"$HOME\"/.tmux/plugins/taimux*/ \"$HOME\"/.config/tmux/plugins/taimux*/; do \
43     [ -x \"$d/taimux\" ] && PATH=\"$PATH:${d%/}\"; done; \
44     command -v taimux >/dev/null 2>&1 || exit 127; exec taimux";
45
46/// The preamble, for a caller that needs to build its own remote command.
47pub fn remote_taimux() -> &'static str {
48    REMOTE_TAIMUX
49}
50
51/// The subcommand `index_fetch` asks a remote host for.
52///
53/// Named rather than inlined so the test below can assert it against the
54/// dispatcher, because nothing else can: a wrong name here is answered with
55/// `no such command` and exit 1, which `index_fetch` cannot tell apart from an
56/// old host with nothing to say. It stayed wrong for exactly that reason.
57const INDEX_DUMP_CMD: &str = "index-dump";
58
59/// What `fetch` asks a remote host for: its rows, with the ninth field saying
60/// when each session last said something.
61///
62/// A taimux too old to know `--since` ignores it, since `list` reads no
63/// arguments, and answers the eight fields it always did, which `render` takes
64/// as they are. So asking for more costs an older host nothing.
65const LIST_CMD: &str = "list --since";
66
67fn now() -> i64 {
68    SystemTime::now()
69        .duration_since(UNIX_EPOCH)
70        .map(|d| d.as_secs() as i64)
71        .unwrap_or(0)
72}
73
74pub fn enabled() -> bool {
75    env::on("TAIMUX_REMOTE")
76}
77
78/// Run something with a deadline, and kill it when the deadline passes.
79///
80/// The time limit is the ONLY way out of a popup whose helper wedges: a child
81/// that swallows ctrl-c cannot be escaped from, because the parent waits for it
82/// either way. So nothing on the picker's path may be given a long one.
83fn bounded(secs: u64, mut cmd: Command) -> (i32, String) {
84    let Ok(mut child) = cmd.stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else {
85        return (255, String::new());
86    };
87    let deadline = Instant::now() + Duration::from_secs(secs);
88    let mut out = child.stdout.take();
89    loop {
90        match child.try_wait() {
91            Ok(Some(st)) => {
92                let mut s = String::new();
93                if let Some(o) = out.as_mut() {
94                    let _ = o.read_to_string(&mut s);
95                }
96                return (st.code().unwrap_or(255), s);
97            }
98            Ok(None) => {
99                if Instant::now() >= deadline {
100                    let _ = child.kill();
101                    let _ = child.wait();
102                    return (124, String::new()); // the status `timeout` uses
103                }
104                std::thread::sleep(Duration::from_millis(20));
105            }
106            Err(_) => return (255, String::new()),
107        }
108    }
109}
110
111/// One ssh, bounded, batch-mode, and never reading stdin: `-n` matters because
112/// this runs behind a picker that owns the terminal.
113pub fn ssh(host: &str, remote: &str, timeout: u64) -> (i32, String) {
114    let mut c = Command::new("ssh");
115    c.args([
116        "-n",
117        "-o",
118        "BatchMode=yes",
119        "-o",
120        &format!(
121            "ConnectTimeout={}",
122            env::num("TAIMUX_SSH_CONNECT_TIMEOUT", 2)
123        ),
124        "--",
125        host,
126        remote,
127    ]);
128    taimux_core::stat::ssh(|| bounded(timeout, c))
129}
130
131/// Why an ssh failed, in the words the row will carry.
132pub fn ssh_why(status: i32) -> &'static str {
133    match status {
134        127 => "no taimux on that host",
135        124 | 137 => "timed out",
136        255 => "unreachable",
137        _ => "ssh failed",
138    }
139}
140
141/// The host an `ssh … tmux …` argv connects to, or None.
142///
143/// Finds the ssh token, then takes the first bare word after it as the host,
144/// skipping options and the values of the ones that take a separate argument.
145/// `tmux` has to appear AFTER that: it is what separates a pane holding a nested
146/// SERVER from one merely running a remote command (`ssh host journalctl -f`),
147/// and from a plain remote login shell, neither of which has anything to
148/// federate.
149///
150/// **ssh is looked for as a TOKEN rather than as argv[0]**, because it routinely
151/// is not argv[0]: when a `#!` script is named ssh (a ProxyCommand or kerberos
152/// wrapper, and the stand-in the demo uses) the kernel runs it as
153/// `bash /path/to/ssh host …`, so the interpreter holds argv[0] and requiring
154/// that to read "ssh" silently found no hosts at all on such a machine.
155pub fn ssh_host(argv: &str) -> Option<String> {
156    // the options that take a separate value, so the value is not read as a host
157    const TAKES_VALUE: &str = "BbcDEeFIiJLlmOopQRSWw";
158    let toks: Vec<&str> = argv.split(' ').filter(|t| !t.is_empty()).collect();
159    let mut saw_ssh = false;
160    let mut host: Option<&str> = None;
161    let mut saw_tmux = false;
162    let mut i = 0;
163    while i < toks.len() {
164        let tok = toks[i];
165        if !saw_ssh {
166            let base = tok.rsplit('/').next().unwrap_or(tok);
167            if base == "ssh" {
168                saw_ssh = true;
169            }
170            i += 1;
171            continue;
172        }
173        if host.is_none() {
174            if tok.starts_with('-') {
175                let mut c = tok.chars();
176                c.next();
177                if let (Some(f), None) = (c.next(), c.next()) {
178                    if TAKES_VALUE.contains(f) {
179                        i += 1; // its value is not a host
180                    }
181                }
182                i += 1;
183                continue;
184            }
185            host = Some(tok);
186            i += 1;
187            continue;
188        }
189        if tok == "tmux" {
190            saw_tmux = true;
191        }
192        i += 1;
193    }
194    let host = host?;
195    if !saw_tmux {
196        return None;
197    }
198    // Anything unexpected in a host is dropped rather than escaped: the name
199    // becomes a cache filename and an ssh argument, and there is no such thing as
200    // a hostname needing a quote.
201    if host.is_empty()
202        || !host
203            .bytes()
204            .all(|b| b.is_ascii_alphanumeric() || b"._@-".contains(&b))
205    {
206        return None;
207    }
208    Some(host.to_string())
209}
210
211/// host and the local pane it is reached through, for every ssh pane.
212pub fn ssh_tmux_panes(panes: &[(String, String)]) -> Vec<(String, String)> {
213    // The foreground argv per tty, which is the same scan the pane list uses. A
214    // tty can carry more than one foreground-group process, so every one of them
215    // is tried before the pane is written off.
216    let fg = proc::foreground_map();
217    let mut out = Vec::new();
218    for (id, tty) in panes {
219        let tty = tty.trim_start_matches("/dev/");
220        for f in fg.iter().filter(|f| f.tty == tty) {
221            if let Some(h) = ssh_host(&f.argv) {
222                out.push((h, id.clone()));
223                break;
224            }
225        }
226    }
227    out
228}
229
230pub fn cache_dir() -> PathBuf {
231    taimux_core::paths::runtime_dir().join("remote")
232}
233
234/// The host-list cache, keyed by tmux SERVER.
235///
236/// Keyed because that is what it is a property of: the list comes off that
237/// server's panes, and a second server on the same box (the demo runs one) has
238/// entirely different ones.
239fn hosts_file(dir: &Path) -> PathBuf {
240    let sock = std::env::var("TMUX").unwrap_or_default();
241    let sock = sock.split(',').next().unwrap_or("").to_string();
242    if sock.is_empty() {
243        dir.join(".hosts")
244    } else {
245        dir.join(format!(".hosts.{}", sock.replace('/', "%")))
246    }
247}
248
249/// Write a file by rename, because two pickers can be open at once and half a
250/// file is worse than an old one.
251fn write_atomic(f: &Path, body: &str) {
252    if let Some(d) = f.parent() {
253        let _ = std::fs::create_dir_all(d);
254    }
255    let tmp = f.with_extension(format!("t{}", std::process::id()));
256    if std::fs::write(&tmp, body).is_ok() && !body.is_empty() && std::fs::rename(&tmp, f).is_ok() {
257        return;
258    }
259    let _ = std::fs::remove_file(&tmp);
260}
261
262/// A cached file's header: `<status> <epoch> [reason]`.
263///
264/// One line, so a reader learns both what happened and how old it is from ONE
265/// read: no stat, no fork. That matters because the freshness test runs per host
266/// on every refresh tick.
267fn header(f: &Path) -> Option<(String, i64, String)> {
268    let text = std::fs::read_to_string(f).ok()?;
269    let line = text.lines().next()?;
270    let mut it = line.splitn(3, ' ');
271    let status = it.next()?.to_string();
272    let stamp = it.next().and_then(|s| s.parse().ok()).unwrap_or(0);
273    Some((status, stamp, it.next().unwrap_or("").to_string()))
274}
275
276/// The discovered hosts, cached.
277///
278/// Discovery is a full process scan and it answers the same thing tick after
279/// tick, since panes do not open and close on the timescale a picker refreshes
280/// on. Caching it keeps the steady-state cost of federation to reading a few
281/// small files, and keeps that cost OFF everyone else: without it a server with
282/// no ssh panes at all still pays a scan on every refresh to find that out.
283pub fn hosts_cached(dir: &Path, panes: &[(String, String)]) -> Vec<String> {
284    let f = hosts_file(dir);
285    if let Some((status, stamp, _)) = header(&f) {
286        if status == "hosts" && now() - stamp < env::num("TAIMUX_HOSTS_TTL", 5) as i64 {
287            return std::fs::read_to_string(&f)
288                .unwrap_or_default()
289                .lines()
290                .skip(1)
291                .filter(|l| !l.is_empty())
292                .map(|l| l.to_string())
293                .collect();
294        }
295    }
296    let mut hosts: Vec<String> = ssh_tmux_panes(panes).into_iter().map(|(h, _)| h).collect();
297    hosts.sort();
298    hosts.dedup();
299    // The header line is unconditional, so the file is never empty and the write
300    // is never mistaken for a failure. bash got this wrong the other way round:
301    // its `if { … } > tmp` tested the LAST command in the group, which was the
302    // "are there any hosts?" guard, so on every server with nothing to federate
303    // the write read as failed, the cache was never written, and each refresh both
304    // re-ran the scan the cache exists to avoid and left its temp file behind.
305    write_atomic(&f, &format!("hosts {}\n{}\n", now(), hosts.join("\n")));
306    hosts
307}
308
309/// Ask one host about itself, and write down what it said.
310pub fn fetch(host: &str, dir: &Path) {
311    let (rc, out) = ssh(
312        host,
313        &format!("{} {}", REMOTE_TAIMUX, LIST_CMD),
314        env::num("TAIMUX_SSH_TIMEOUT", 4),
315    );
316    let f = dir.join(host);
317    if rc == 0 {
318        write_atomic(&f, &format!("ok {}\n{}", now(), out));
319        // A host that has answered ONCE is a participant, and from then on its
320        // silence is worth a row. One that has never answered is simply not
321        // running taimux, which is a permanent and perfectly fine state of
322        // affairs rather than an outage, so it stays out of the list entirely
323        // instead of parking a complaint in it. Install taimux there and the
324        // host joins on its own; that is the whole of the configuration.
325        let _ = std::fs::write(dir.join(format!("{}.seen", host)), "");
326    } else {
327        write_atomic(&f, &format!("err {} {}\n", now(), ssh_why(rc)));
328    }
329}
330
331/// One host's cached reply, turned into rows.
332///
333/// A row's pane id becomes `<host>:<pane>`. The host rides INSIDE the id rather
334/// than in a column of its own because that id is the only thing the picker
335/// carries downstream, so one composite string keeps preview, switch and restart
336/// unchanged and costs `list` no schema change.
337pub fn render(host: &str, dir: &Path) -> String {
338    let f = dir.join(host);
339    let Some((status, _, reason)) = header(&f) else {
340        return String::new();
341    };
342    let text = std::fs::read_to_string(&f).unwrap_or_default();
343    let mut s = String::new();
344    if status == "ok" {
345        let mut bad = 0;
346        for line in text.lines().skip(1) {
347            if line.is_empty() {
348                continue;
349            }
350            // Eight fields from a host that predates `--since`, nine from one
351            // that answered it. Anything else is a shape this build cannot read.
352            if matches!(line.split('\t').count(), 8 | 9) {
353                s.push_str(&format!("{}:{}\n", host, line));
354            } else {
355                bad += 1;
356            }
357        }
358        // A taimux over there answers in another shape. Say so on one row rather
359        // than dropping its sessions silently.
360        if bad > 0 {
361            s.push_str(&format!(
362                "{}:!\t{}\t-\t-\t\tunknown\t-\tits taimux answers in another format ({} row(s) dropped)\n",
363                host, host, bad
364            ));
365        }
366    } else if dir.join(format!("{}.seen", host)).exists() {
367        s.push_str(&format!(
368            "{}:!\t{}\t-\t-\t\tunknown\t-\t{}\n",
369            host,
370            host,
371            if reason.is_empty() {
372                "unreachable"
373            } else {
374                &reason
375            }
376        ));
377    }
378    s
379}
380
381/// Which hosts need asking, and how urgently.
382///
383/// Split out so the TTLs can be asserted without an ssh anywhere near it. The
384/// two are deliberately far apart: an answer is worth three seconds, a FAILURE
385/// sixty, because a sleeping host must not be re-probed on every tick while a
386/// live one must not go stale.
387///
388/// A file with no header at all, or a header this does not recognise, is COLD
389/// rather than stale: it has never answered, so serving it from cache would mean
390/// serving nothing.
391fn classify(hosts: &[String], dir: &Path, n: i64) -> (Vec<String>, Vec<String>) {
392    let (mut cold, mut stale) = (Vec::new(), Vec::new());
393    for h in hosts {
394        match header(&dir.join(h)) {
395            None => cold.push(h.clone()),
396            Some((status, stamp, _)) => {
397                let ttl = match status.as_str() {
398                    "ok" => env::num("TAIMUX_REMOTE_TTL", 3),
399                    "err" => env::num("TAIMUX_REMOTE_FAIL_TTL", 60),
400                    _ => {
401                        cold.push(h.clone());
402                        continue;
403                    }
404                };
405                if n - stamp >= ttl as i64 {
406                    stale.push(h.clone());
407                }
408            }
409        }
410    }
411    (cold, stale)
412}
413
414/// Every discovered host's rows.
415pub fn rows(panes: &[(String, String)]) -> String {
416    if !enabled() {
417        return String::new();
418    }
419    let dir = cache_dir();
420    let hosts = hosts_cached(&dir, panes);
421    if hosts.is_empty() {
422        return String::new();
423    }
424
425    let (cold, stale) = classify(&hosts, &dir, now());
426
427    // Nothing cached at all: fetched NOW, and in parallel, so n hosts cost one
428    // round trip rather than n. Serving that host from cache would mean serving
429    // nothing, and the first picker opened after a reboot would come up missing
430    // exactly the remote sessions it was opened to find. Once per host per boot.
431    let mut handles = Vec::new();
432    for h in cold {
433        let d = dir.clone();
434        handles.push(std::thread::spawn(move || fetch(&h, &d)));
435    }
436    for j in handles {
437        let _ = j.join();
438    }
439
440    // An answer that is merely ageing is served as it stands and refreshed
441    // BEHIND the picker, so the wait lands on the next tick instead of on this
442    // one. Detached, and nothing here waits for them.
443    for h in stale {
444        let d = dir.clone();
445        std::thread::spawn(move || fetch(&h, &d));
446    }
447
448    hosts.iter().map(|h| render(h, &dir)).collect()
449}
450
451/// The pane the picker was opened from, resolved through an ssh window.
452///
453/// If that pane is a window onto another host, the row you are on is over THERE,
454/// not the ssh pane you are looking through.
455pub fn resolve_cur(pane: &str, panes: &[(String, String)], pane_cmd: &str) -> String {
456    if !pane.starts_with('%') || !enabled() {
457        return pane.to_string();
458    }
459    // Cheap pre-filter: only a pane whose foreground is ssh can be a window onto
460    // another server, and the scan behind that question is a process listing.
461    if pane_cmd != "ssh" {
462        return pane.to_string();
463    }
464    let Some((host, _)) = ssh_tmux_panes(panes).into_iter().find(|(_, p)| p == pane) else {
465        return pane.to_string();
466    };
467    // A host already known to be down is not asked again: the list has just
468    // waited on that same host, and paying its timeout a second time to place a
469    // cursor is not a trade worth making.
470    if let Some((status, _, _)) = header(&cache_dir().join(&host)) {
471        if status == "err" {
472            return pane.to_string();
473        }
474    }
475    let (rc, out) = ssh(
476        &host,
477        "tmux display-message -p \"#{pane_id}\"",
478        env::num("TAIMUX_SSH_CUR_TIMEOUT", 2),
479    );
480    let rid = out.trim();
481    if rc == 0 && rid.starts_with('%') {
482        format!("{}:{}", host, rid)
483    } else {
484        pane.to_string()
485    }
486}
487
488/// This host's index, for another host to read: `<pane> \t <blob>` per line.
489///
490/// Only LOCAL panes, which is the same "federate, never reach in" rule: a host
491/// must never answer with another host's rows.
492pub fn index_dump() -> String {
493    let mut s = String::new();
494    for e in std::fs::read_dir(index::index_dir())
495        .into_iter()
496        .flatten()
497        .flatten()
498    {
499        let Ok(text) = std::fs::read_to_string(e.path()) else {
500            continue;
501        };
502        let mut lines = text.lines();
503        let Some(head) = lines.next() else { continue };
504        let f: Vec<&str> = head.split(' ').collect();
505        if f.first() != Some(&"idx") || f.len() < 4 {
506            continue;
507        }
508        let pane = f[3];
509        if !(pane.starts_with('%') && pane[1..].bytes().all(|b| b.is_ascii_digit())) {
510            continue;
511        }
512        s.push_str(&format!("{}\t{}\n", pane, lines.next().unwrap_or("")));
513    }
514    s
515}
516
517/// Fetch one host's index and write it under composite ids.
518///
519/// A host whose taimux predates all of this answers with a usage line on stderr
520/// and nothing here, so nothing is written and its rows go on matching what they
521/// show. The guard on the pane id is what makes that a non-event.
522///
523/// That tolerance is also how this went unnoticed: the request used to carry an
524/// underscore-prefixed bash-era name no Rust build has ever implemented, so EVERY
525/// host answered `no such command` and exited 1, and the `rc != 0` below read it
526/// as "an old host, nothing to see". The name has to match a subcommand in
527/// main.rs exactly, which is why it is the named constant below and why the
528/// suite asserts the old spelling appears nowhere in this file.
529pub fn index_fetch(host: &str, dir: &Path) {
530    let (rc, out) = ssh(
531        host,
532        &format!("{} {}", REMOTE_TAIMUX, INDEX_DUMP_CMD),
533        env::num("TAIMUX_SEARCH_SSH_TIMEOUT", 20),
534    );
535    if rc != 0 {
536        return;
537    }
538    let n = now();
539    for line in out.lines() {
540        let Some((pane, blob)) = line.split_once('\t') else {
541            continue;
542        };
543        if !(pane.starts_with('%') && pane[1..].bytes().all(|b| b.is_ascii_digit())) {
544            continue;
545        }
546        let id = format!("{}:{}", host, pane);
547        let f = dir.join(index::key_for(&id));
548        let _ = std::fs::write(&f, format!("idx 0 {} {} -\n{}\n", n, id, blob));
549    }
550}
551
552/// Every discovered host's index, on its own longer TTL.
553///
554/// A minute rather than the three seconds a LIST is worth: what was said in a
555/// session does not go stale on the timescale a pane's state does.
556pub fn index_remote(panes: &[(String, String)]) {
557    if !enabled() || !env::on("TAIMUX_SEARCH_REMOTE") {
558        return;
559    }
560    let dir = index::index_dir();
561    let ttl = env::num("TAIMUX_SEARCH_REMOTE_TTL", 60) as i64;
562    let n = now();
563    for h in hosts_cached(&cache_dir(), panes) {
564        let stampfile = dir.join(format!(".{}.stamp", h));
565        let last: i64 = std::fs::read_to_string(&stampfile)
566            .ok()
567            .and_then(|s| s.trim().parse().ok())
568            .unwrap_or(0);
569        if n - last < ttl {
570            continue;
571        }
572        let _ = std::fs::create_dir_all(&dir);
573        let _ = std::fs::write(&stampfile, format!("{}\n", n));
574        index_fetch(&h, &dir);
575    }
576}
577
578/// A row's pane id is either a local `%17` or a remote `<host>:%6`.
579pub fn pane_host(id: &str) -> Option<&str> {
580    if id.is_empty() || id.starts_with('%') {
581        return None;
582    }
583    id.split_once(':').map(|(h, _)| h)
584}
585
586pub fn pane_local(id: &str) -> &str {
587    if id.is_empty() || id.starts_with('%') {
588        return id;
589    }
590    id.split_once(':').map(|(_, p)| p).unwrap_or(id)
591}
592
593/// Drive another host's tmux AS A PEER, then bring the local client to its ssh
594/// pane.
595///
596/// **In that order**, so the pane is already showing the right window by the time
597/// the local client arrives in it. The other way round, a jump lands on whatever
598/// that host was last looking at and corrects itself a moment later.
599pub fn switch_remote(host: &str, lid: &str, local_pane: &str, zoom: bool) -> Result<(), String> {
600    if !lid.starts_with('%') {
601        return Err("not a pane id".into());
602    }
603    if local_pane.is_empty() {
604        return Err(format!("nothing is ssh'd into {} any more", host));
605    }
606    let mut remote = format!(
607        "tmux select-window -t {0} \\; select-pane -t {0} \\; switch-client -t {0}",
608        lid
609    );
610    if zoom {
611        // resize-pane -Z TOGGLES, so it is asked first, exactly as the local
612        // path does.
613        remote.push_str(&format!(
614            "\n[ \"$(tmux display-message -p -t {0} '#{{window_zoomed_flag}}')\" = 1 ] || tmux resize-pane -Z -t {0}",
615            lid
616        ));
617    }
618    let (rc, _) = ssh(host, &remote, env::num("TAIMUX_SSH_TIMEOUT", 4));
619    // A host that has gone quiet since the list was built still gets you taken
620    // to its pane: that is where the dead connection is, and where you would go
621    // to deal with it. Only the remote half is lost, and not silently.
622    let lost = rc != 0;
623    if taimux_core::tmux::switch_local(local_pane, zoom) {
624        if lost {
625            Err(format!("{} did not answer, going to its pane anyway", host))
626        } else {
627            Ok(())
628        }
629    } else {
630        Err(format!("could not reach {}", local_pane))
631    }
632}
633
634/// pane id and tty for every pane on this server, which is what the discovery
635/// scan needs and what the caller already has.
636pub fn tmux_pane_ttys() -> Vec<(String, String)> {
637    taimux_core::tmux::ask_raw(&["list-panes", "-a", "-F", "#{pane_id}\t#{pane_tty}"])
638        .unwrap_or_default()
639        .lines()
640        .filter_map(|l| l.split_once('\t'))
641        .map(|(a, b)| (a.to_string(), b.to_string()))
642        .collect()
643}
644
645/// The whole list: this server's agent panes plus every discovered host's.
646pub fn all_panes(local: &str, panes: &[(String, String)]) -> String {
647    format!("{}{}", local, rows(panes))
648}
649
650#[cfg(test)]
651mod tests {
652    use super::*;
653
654    #[test]
655    fn an_ssh_tmux_argv_names_its_host() {
656        assert_eq!(
657            ssh_host("ssh ha -t tmux new-session -As main").as_deref(),
658            Some("ha")
659        );
660        assert_eq!(
661            ssh_host("/usr/bin/ssh laptop-two -t tmux attach").as_deref(),
662            Some("laptop-two")
663        );
664    }
665
666    /// ssh is a TOKEN, not argv[0]: a `#!` wrapper named ssh runs as
667    /// `bash /path/to/ssh host …`, and requiring argv[0] found no hosts at all
668    /// on such a machine.
669    #[test]
670    fn ssh_is_found_when_it_is_not_argv_zero() {
671        assert_eq!(
672            ssh_host("bash /home/p/bin/ssh ha -t tmux attach").as_deref(),
673            Some("ha")
674        );
675    }
676
677    /// A later `tmux` is required, or `ssh host journalctl -f` and a plain remote
678    /// login shell would both look like a window onto another server.
679    #[test]
680    fn without_a_later_tmux_it_is_not_a_window_onto_a_server() {
681        assert_eq!(ssh_host("ssh ha journalctl -f"), None);
682        assert_eq!(ssh_host("ssh ha"), None);
683        assert_eq!(ssh_host("tmux attach"), None);
684        assert_eq!(ssh_host(""), None);
685    }
686
687    /// An option that takes a separate value must not have that value read as
688    /// the host.
689    #[test]
690    fn an_options_value_is_not_mistaken_for_a_host() {
691        assert_eq!(
692            ssh_host("ssh -p 2222 ha -t tmux attach").as_deref(),
693            Some("ha")
694        );
695        assert_eq!(
696            ssh_host("ssh -i /k/id_ed25519 -o Foo=bar ha tmux attach").as_deref(),
697            Some("ha")
698        );
699        // a flag with no separate value is skipped without eating the host
700        assert_eq!(ssh_host("ssh -4 -A ha tmux attach").as_deref(), Some("ha"));
701    }
702
703    /// The name becomes a cache filename and an ssh argument, and there is no
704    /// such thing as a hostname needing a quote.
705    #[test]
706    fn an_unexpected_character_in_a_host_drops_it() {
707        assert_eq!(ssh_host("ssh ha;rm -rf / tmux attach"), None);
708        assert_eq!(ssh_host("ssh ../etc tmux attach"), None);
709        assert_eq!(ssh_host("ssh $HOST tmux attach"), None);
710        // …but the ordinary shapes are fine
711        assert_eq!(
712            ssh_host("ssh user@ha.example.com tmux attach").as_deref(),
713            Some("user@ha.example.com")
714        );
715    }
716
717    #[test]
718    fn a_composite_id_splits_into_host_and_pane() {
719        assert_eq!(pane_host("ha:%6"), Some("ha"));
720        assert_eq!(pane_local("ha:%6"), "%6");
721        assert_eq!(pane_host("%17"), None);
722        assert_eq!(pane_local("%17"), "%17");
723        assert_eq!(pane_host(""), None);
724        assert_eq!(pane_local(""), "");
725        // the note row a host that stopped answering keeps
726        assert_eq!(pane_host("ha:!"), Some("ha"));
727        assert_eq!(pane_local("ha:!"), "!");
728    }
729
730    #[test]
731    fn an_ssh_failure_says_what_kind() {
732        assert_eq!(ssh_why(127), "no taimux on that host");
733        assert_eq!(ssh_why(124), "timed out");
734        assert_eq!(ssh_why(137), "timed out");
735        assert_eq!(ssh_why(255), "unreachable");
736        assert_eq!(ssh_why(3), "ssh failed");
737    }
738
739    fn fixture(tag: &str) -> PathBuf {
740        let d = std::env::temp_dir().join(format!("jmrem{}{}", std::process::id(), tag));
741        let _ = std::fs::remove_dir_all(&d);
742        std::fs::create_dir_all(&d).unwrap();
743        d
744    }
745
746    #[test]
747    fn a_cached_reply_becomes_host_prefixed_rows() {
748        let d = fixture("r");
749        std::fs::write(
750            d.join("ha"),
751            "ok 100\n%6\tmain:1.7\t/w\tclaude\t2.1.1\trun\t-\tover there\n",
752        )
753        .unwrap();
754        let out = render("ha", &d);
755        assert!(out.starts_with("ha:%6\tmain:1.7\t"));
756        assert_eq!(out.lines().count(), 1);
757        let _ = std::fs::remove_dir_all(&d);
758    }
759
760    /// A host that answered `list --since` sends a ninth field, when the session
761    /// last said something, and its rows are taken whole. One too old for the
762    /// flag answers the eight above, which is just as readable.
763    #[test]
764    fn a_reply_carrying_the_last_message_is_taken_whole() {
765        let d = fixture("n");
766        std::fs::write(
767            d.join("ha"),
768            "ok 100\n%6\tmain:1.7\t/w\tclaude\t2.1.1\tidle\t-\tover there\t1700000000000\n",
769        )
770        .unwrap();
771        assert_eq!(
772            render("ha", &d),
773            "ha:%6\tmain:1.7\t/w\tclaude\t2.1.1\tidle\t-\tover there\t1700000000000\n"
774        );
775        assert!(LIST_CMD.starts_with("list ") && LIST_CMD.ends_with(" --since"));
776        let _ = std::fs::remove_dir_all(&d);
777    }
778
779    /// A host that has answered before and then goes quiet keeps ONE row saying
780    /// so. One that never answered gets none: it is simply not running taimux,
781    /// which is not an outage.
782    #[test]
783    fn only_a_host_that_has_answered_before_keeps_a_row() {
784        let d = fixture("e");
785        std::fs::write(d.join("ha"), "err 100 unreachable\n").unwrap();
786        assert_eq!(render("ha", &d), "");
787        std::fs::write(d.join("ha.seen"), "").unwrap();
788        let out = render("ha", &d);
789        assert!(out.starts_with("ha:!\tha\t"));
790        assert!(out.contains("unreachable"));
791        let _ = std::fs::remove_dir_all(&d);
792    }
793
794    /// An older taimux over there answers in another shape. Say so on one row
795    /// rather than dropping its sessions silently.
796    #[test]
797    fn a_reply_in_another_format_says_so_once() {
798        let d = fixture("f");
799        std::fs::write(
800            d.join("ha"),
801            "ok 100\n%6\ttoo\tfew\tfields\n%7\talso\tshort\n",
802        )
803        .unwrap();
804        let out = render("ha", &d);
805        assert_eq!(out.lines().count(), 1);
806        assert!(out.contains("2 row(s) dropped"));
807        let _ = std::fs::remove_dir_all(&d);
808    }
809
810    #[test]
811    fn a_file_with_no_header_renders_nothing() {
812        let d = fixture("h");
813        assert_eq!(render("ha", &d), ""); // no file at all
814        std::fs::write(d.join("ha"), "").unwrap();
815        assert_eq!(render("ha", &d), "");
816        let _ = std::fs::remove_dir_all(&d);
817    }
818
819    /// The header is unconditional, so the file is never empty and the write is
820    /// never mistaken for a failure. bash tested the last command in a group,
821    /// which was the "any hosts?" guard, so every server with nothing to
822    /// federate re-ran the scan forever and left temp files behind.
823    #[test]
824    fn the_host_cache_is_written_even_with_no_hosts() {
825        // TMUX is process-global and the harness runs threads: two tests
826        // setting it at once read each other's key. Same lock as everywhere else.
827        let _g = taimux_core::env::ENV_LOCK.lock().unwrap();
828        let d = fixture("c");
829        std::env::set_var("TMUX", "/tmp/sock,1,0");
830        let hosts = hosts_cached(&d, &[]);
831        assert!(hosts.is_empty());
832        let f = hosts_file(&d);
833        assert!(f.exists(), "no cache file was written");
834        assert!(std::fs::read_to_string(&f).unwrap().starts_with("hosts "));
835        // and nothing was left behind
836        let left: Vec<String> = std::fs::read_dir(&d)
837            .unwrap()
838            .flatten()
839            .map(|e| e.file_name().to_string_lossy().into_owned())
840            .filter(|n| n.contains(".t"))
841            .collect();
842        assert!(left.is_empty(), "temp files left: {:?}", left);
843        std::env::remove_var("TMUX");
844        let _ = std::fs::remove_dir_all(&d);
845    }
846
847    /// Keyed by tmux SERVER: the list comes off that server's panes, and a second
848    /// server on the same box has entirely different ones.
849    #[test]
850    fn the_host_cache_is_keyed_by_server() {
851        // TMUX is process-global and the harness runs threads: two tests
852        // setting it at once read each other's key. Same lock as everywhere else.
853        let _g = taimux_core::env::ENV_LOCK.lock().unwrap();
854        let d = fixture("k");
855        std::env::set_var("TMUX", "/tmp/one,1,0");
856        let a = hosts_file(&d);
857        std::env::set_var("TMUX", "/tmp/two,1,0");
858        let b = hosts_file(&d);
859        assert_ne!(a, b);
860        std::env::remove_var("TMUX");
861        let _ = std::fs::remove_dir_all(&d);
862    }
863
864    /// The time limit is the ONLY way out of a popup whose helper wedges: a
865    /// child that swallows ctrl-c cannot be escaped from, because the parent
866    /// waits for it either way. So this has to actually kill.
867    #[test]
868    fn a_wedged_child_is_killed_rather_than_waited_for() {
869        let mut c = Command::new("sleep");
870        c.arg("30");
871        let started = Instant::now();
872        let (rc, out) = bounded(1, c);
873
874        // `bounded` answers 255 for three different things: the spawn failed,
875        // the child was signalled rather than exiting, and `try_wait` errored.
876        // None of them is what this test is about, and all three come back
877        // IMMEDIATELY, where the path under test cannot return before its
878        // deadline. Under the fork pressure of the whole suite running in
879        // parallel that happens about once in twelve runs; alone, never in
880        // sixty. Conflating them in production is right (a failed ssh really is
881        // "unreachable"), so the telling apart belongs here.
882        if rc == 255 && started.elapsed() < Duration::from_millis(500) {
883            eprintln!(
884                "no child was spawned to wedge, skipping: rc={} in {:?}",
885                rc,
886                started.elapsed()
887            );
888            return;
889        }
890
891        assert_eq!(
892            rc,
893            124,
894            "not the status `timeout` uses; came back in {:?}",
895            started.elapsed()
896        );
897        assert!(out.is_empty());
898        assert!(
899            started.elapsed() < Duration::from_secs(5),
900            "waited {:?} for a 1 s limit",
901            started.elapsed()
902        );
903    }
904
905    /// `bounded`, for a child that is supposed to start: `None` when it never
906    /// did, rather than the answer a failed fork is indistinguishable from.
907    ///
908    /// The same conflation the test above steps around, met from the other side.
909    /// There a spawn failure could be told apart by the clock, since the path
910    /// under test cannot return before its deadline; here the child is a `printf`
911    /// that returns at once either way, so the only thing left is that a fork
912    /// this machine refused is **transient**. It was refused for want of a slot
913    /// under the suite's own parallelism, not because anything about the child is
914    /// wrong, so it is worth simply asking again: five tries 50ms apart against a
915    /// failure rate the neighbour measures at about one run in twelve.
916    ///
917    /// Not fixed in `bounded` itself. Answering 255 for a child that never
918    /// started is right for its caller, where a failed ssh and an unreachable
919    /// host are the same thing, and a status invented for the benefit of a test
920    /// would be a different tool under the picker.
921    fn spawned(secs: u64, make: impl Fn() -> Command) -> Option<(i32, String)> {
922        for _ in 0..5 {
923            let got = bounded(secs, make());
924            if got != (255, String::new()) {
925                return Some(got);
926            }
927            std::thread::sleep(Duration::from_millis(50));
928        }
929        None
930    }
931
932    /// Said out loud, because a check that quietly does not run is worse than
933    /// one that fails.
934    fn no_fork() {
935        eprintln!("bounded: no child could be spawned in five tries, skipping");
936    }
937
938    #[test]
939    fn a_prompt_child_runs_to_completion_and_its_output_comes_back() {
940        let Some(got) = spawned(5, || {
941            let mut c = Command::new("printf");
942            c.arg("hi");
943            c
944        }) else {
945            return no_fork();
946        };
947        assert_eq!(got, (0, "hi".to_string()));
948        // …and a non-zero status is reported as its own, not as a timeout
949        let Some(got) = spawned(5, || Command::new("false")) else {
950            return no_fork();
951        };
952        assert_eq!(got.0, 1);
953        // A program that is not there is unreachable-shaped rather than a panic,
954        // and this one asks `bounded` directly: the shape `spawned` retries IS
955        // the answer here, so going through it would be waiting out five
956        // deliberate failures to arrive at the same 255.
957        let c = Command::new("no-such-program-at-all");
958        assert_eq!(bounded(5, c).0, 255);
959    }
960
961    /// The other half of `spawned`'s contract, and the only thing that ever runs
962    /// its give-up arm on a machine that can fork: five failures in a row are
963    /// reported as no answer, never as the 255 they are made of.
964    #[test]
965    fn a_child_that_never_starts_is_no_answer_at_all() {
966        assert_eq!(spawned(5, || Command::new("no-such-program-at-all")), None);
967    }
968
969    /// The TTL split, without an ssh anywhere near it. An answer is worth three
970    /// seconds and a FAILURE sixty, because a sleeping host must not be
971    /// re-probed on every tick while a live one must not go stale.
972    #[test]
973    fn a_fresh_answer_is_left_alone_and_a_stale_one_is_refreshed() {
974        let d = fixture("q");
975        std::fs::write(d.join("fresh"), "ok 1000\n").unwrap();
976        std::fs::write(d.join("stale"), "ok 900\n").unwrap();
977        std::fs::write(d.join("dead"), "err 995 unreachable\n").unwrap();
978        std::fs::write(d.join("junk"), "nonsense\n").unwrap();
979        let hosts: Vec<String> = ["fresh", "stale", "dead", "junk", "never"]
980            .iter()
981            .map(|s| s.to_string())
982            .collect();
983        let (cold, refresh) = classify(&hosts, &d, 1001);
984        // never asked, and a header nobody recognises: both COLD, because
985        // serving them from cache would mean serving nothing
986        assert_eq!(cold, vec!["junk", "never"]);
987        // 101 s past a 3 s answer, but only 6 s past a 60 s failure
988        assert_eq!(refresh, vec!["stale"]);
989        let _ = std::fs::remove_dir_all(&d);
990    }
991
992    /// The preamble is what runs on the FAR side, and it has three jobs: find a
993    /// taimux that a non-interactive ssh's PATH does not reach, fall back to a
994    /// plugin checkout, and exit 127 when there is none so "no taimux over
995    /// there" is told apart from "unreachable".
996    #[test]
997    fn the_remote_preamble_finds_a_taimux_or_exits_127() {
998        let home = fixture("p");
999        let run = || -> (i32, String) {
1000            let out = Command::new("sh")
1001                .args(["-c", REMOTE_TAIMUX])
1002                .arg("list")
1003                .env("HOME", &home)
1004                .env("PATH", "/usr/bin:/bin")
1005                .output()
1006                .expect("sh");
1007            (
1008                out.status.code().unwrap_or(-1),
1009                String::from_utf8_lossy(&out.stdout).trim().to_string(),
1010            )
1011        };
1012        // nothing installed at all
1013        assert_eq!(run().0, 127);
1014
1015        // a plugin checkout is enough
1016        let plug = home.join(".tmux/plugins/taimux-9f2c1b");
1017        std::fs::create_dir_all(&plug).unwrap();
1018        std::fs::write(
1019            plug.join("taimux"),
1020            "#!/bin/sh\necho answered-from-the-plugin-copy\n",
1021        )
1022        .unwrap();
1023        set_exec(&plug.join("taimux"));
1024        assert_eq!(run(), (0, "answered-from-the-plugin-copy".into()));
1025
1026        // …and a real install still outranks it
1027        let bin = home.join(".local/bin");
1028        std::fs::create_dir_all(&bin).unwrap();
1029        std::fs::write(
1030            bin.join("taimux"),
1031            "#!/bin/sh\necho answered-from-the-real-install\n",
1032        )
1033        .unwrap();
1034        set_exec(&bin.join("taimux"));
1035        assert_eq!(run(), (0, "answered-from-the-real-install".into()));
1036        let _ = std::fs::remove_dir_all(&home);
1037    }
1038
1039    fn set_exec(p: &Path) {
1040        use std::os::unix::fs::PermissionsExt;
1041        let mut m = std::fs::metadata(p).unwrap().permissions();
1042        m.set_mode(0o755);
1043        std::fs::set_permissions(p, m).unwrap();
1044    }
1045
1046    /// A pane that is not an ssh window resolves to itself, and the cheap
1047    /// pre-filter is what stops a process scan on every picker open.
1048    #[test]
1049    fn resolve_cur_leaves_an_ordinary_pane_alone() {
1050        assert_eq!(resolve_cur("%7", &[], "bash"), "%7");
1051        assert_eq!(resolve_cur("%7", &[], "ssh"), "%7"); // ssh, but no host found
1052        assert_eq!(resolve_cur("dead:/x", &[], "ssh"), "dead:/x");
1053    }
1054}