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