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