rmux 0.10.0

A local terminal multiplexer with a tmux-style CLI, daemon runtime, Rust SDK, and ratatui integration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
#![cfg(windows)]

use std::error::Error;
use std::ffi::{OsStr, OsString};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant};

use rmux_pty::{ChildCommand, SpawnedPty, TerminalSize};

#[path = "support/windows_cli_serial.rs"]
mod windows_cli_serial;

const SETUP_TIMEOUT: Duration = Duration::from_secs(8);
const CONTROL_TIMEOUT: Duration = Duration::from_secs(20);

const FORMAT: &str = "#{client_termname}|#{client_termfeatures}|#{client_utf8}|#{client_flags}";
const EXPLICIT_TOP_LEVEL_TERMINAL_ARGS: &[&str] = &["-u", "-2", "-T", "RGB"];
const NO_TOP_LEVEL_ARGS: &[&str] = &[];
const INHERITED_RMUX: &str = r"C:\tmp\outer-rmux,123,0";
const INHERITED_TMUX: &str = r"C:\tmp\outer-tmux,123,0";

#[test]
fn unrelated_starting_pane_does_not_block_a_stable_session_refresh() -> Result<(), Box<dyn Error>> {
    let _serial_guard = windows_cli_serial::acquire("deferred-pane-session-scope")?;
    let binary = PathBuf::from(env!("CARGO_BIN_EXE_rmux"));
    let label = format!("win-deferred-scope-{}", std::process::id());
    let _server = RmuxServerGuard::new(&binary, label.clone());

    run_rmux(
        &binary,
        &label,
        ["new-session", "-d", "-s", "alpha", "cmd.exe", "/D", "/K"],
    )?;
    wait_for_pane_pid(&binary, &label, "alpha", SETUP_TIMEOUT)?;

    run_rmux(
        &binary,
        &label,
        ["new-session", "-d", "-s", "beta", "cmd.exe", "/D", "/K"],
    )?;
    let started = Instant::now();
    run_rmux(&binary, &label, ["select-pane", "-t", "alpha:0.0"])?;

    assert!(
        started.elapsed() < Duration::from_millis(1500),
        "a deferred pane in beta blocked alpha for {:?}",
        started.elapsed()
    );
    Ok(())
}

#[derive(Debug, Clone, Copy)]
struct TerminalProfile {
    name: &'static str,
    term: &'static str,
    term_program: &'static str,
    colorterm: &'static str,
    wt_session: bool,
    top_level_args: &'static [&'static str],
    expected_utf8: &'static str,
    expected_features: &'static [&'static str],
}

#[test]
fn windows_attached_client_terminal_profile_matrix_reports_runtime_features(
) -> Result<(), Box<dyn Error>> {
    let _serial_guard = windows_cli_serial::acquire("attached-client-terminal-profile-matrix")?;
    let _ambient_multiplexer_env = MultiplexerEnvGuard::with_fake_outer();

    for profile in attach_terminal_profiles() {
        let binary = PathBuf::from(env!("CARGO_BIN_EXE_rmux"));
        let label = format!(
            "win-term-matrix-{}-{}",
            sanitize_label(profile.name),
            std::process::id()
        );
        let _server = RmuxServerGuard::new(&binary, label.clone());

        run_rmux(
            &binary,
            &label,
            ["new-session", "-d", "-s", "alpha", "cmd.exe", "/D", "/K"],
        )?;
        run_rmux(&binary, &label, ["set-option", "-g", "status", "off"])?;

        let mut attach = spawn_profile_attach(&binary, &label, "alpha", *profile)?;
        let line = wait_for_attached_client_line(&binary, &label, SETUP_TIMEOUT)?;
        assert_profile_line(profile, &line, false)?;

        terminate_spawned(&mut attach);
    }

    Ok(())
}

#[test]
fn windows_control_mode_terminal_profile_matrix_reports_runtime_features(
) -> Result<(), Box<dyn Error>> {
    let _serial_guard = windows_cli_serial::acquire("control-mode-terminal-profile-matrix")?;
    let _ambient_multiplexer_env = MultiplexerEnvGuard::with_fake_outer();

    for profile in control_terminal_profiles() {
        let binary = PathBuf::from(env!("CARGO_BIN_EXE_rmux"));
        let label = format!(
            "win-control-term-matrix-{}-{}",
            sanitize_label(profile.name),
            std::process::id()
        );
        let _server = RmuxServerGuard::new(&binary, label.clone());

        run_rmux(
            &binary,
            &label,
            ["new-session", "-d", "-s", "alpha", "cmd.exe", "/D", "/K"],
        )?;

        let transcript = run_control_mode_with_profile(
            &binary,
            &label,
            *profile,
            &format!("attach-session -t alpha\nlist-clients -F '{FORMAT}'\n"),
        )?;
        assert!(
            transcript.status.success(),
            "control-mode profile {} failed: status={:?}\nstdout={}\nstderr={}",
            profile.name,
            transcript.status.code(),
            String::from_utf8_lossy(&transcript.stdout),
            String::from_utf8_lossy(&transcript.stderr)
        );
        assert!(
            transcript.stderr.is_empty(),
            "control-mode stderr should stay empty for {}: {}",
            profile.name,
            String::from_utf8_lossy(&transcript.stderr)
        );

        let line = extract_control_payload_line(&transcript.stdout).ok_or_else(|| {
            format!(
                "control-mode profile {} did not emit the list-clients payload; transcript={}",
                profile.name,
                String::from_utf8_lossy(&transcript.stdout)
            )
        })?;
        assert_profile_line(profile, &line, true)?;
    }

    Ok(())
}

fn attach_terminal_profiles() -> &'static [TerminalProfile] {
    &[
        TerminalProfile {
            name: "explicit-vt100-top-level",
            term: "vt100",
            term_program: "",
            colorterm: "",
            wt_session: false,
            top_level_args: EXPLICIT_TOP_LEVEL_TERMINAL_ARGS,
            expected_utf8: "1",
            expected_features: &["256", "RGB"],
        },
        TerminalProfile {
            name: "windows-terminal",
            term: "xterm-256color",
            term_program: "Windows Terminal",
            colorterm: "truecolor",
            wt_session: true,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "1",
            expected_features: &["256", "RGB", "bpaste", "mouse", "sync"],
        },
        TerminalProfile {
            name: "kitty-term-profile",
            term: "xterm-kitty",
            term_program: "",
            colorterm: "",
            wt_session: false,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "0",
            expected_features: &["kitty-graphics", "hyperlinks", "margins", "osc7", "sync"],
        },
        TerminalProfile {
            name: "wezterm-profile",
            term: "wezterm",
            term_program: "WezTerm",
            colorterm: "truecolor",
            wt_session: false,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "0",
            expected_features: &["kitty-graphics", "sixel", "sync", "RGB"],
        },
        TerminalProfile {
            name: "mintty-profile",
            term: "mintty",
            term_program: "mintty",
            colorterm: "",
            wt_session: false,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "0",
            expected_features: &["clipboard", "mouse", "sixel"],
        },
    ]
}

fn control_terminal_profiles() -> &'static [TerminalProfile] {
    &[
        TerminalProfile {
            name: "control-explicit-vt100-top-level",
            term: "vt100",
            term_program: "",
            colorterm: "",
            wt_session: false,
            top_level_args: EXPLICIT_TOP_LEVEL_TERMINAL_ARGS,
            expected_utf8: "1",
            expected_features: &["256", "RGB"],
        },
        TerminalProfile {
            name: "control-windows-terminal",
            term: "xterm-256color",
            term_program: "Windows Terminal",
            colorterm: "truecolor",
            wt_session: true,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "1",
            expected_features: &["bpaste", "mouse", "sync"],
        },
        TerminalProfile {
            name: "control-kitty-term-profile",
            term: "xterm-kitty",
            term_program: "",
            colorterm: "",
            wt_session: false,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "0",
            expected_features: &[],
        },
        TerminalProfile {
            name: "control-wezterm-profile",
            term: "wezterm",
            term_program: "WezTerm",
            colorterm: "truecolor",
            wt_session: false,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "0",
            expected_features: &[],
        },
        TerminalProfile {
            name: "control-mintty-profile",
            term: "mintty",
            term_program: "mintty",
            colorterm: "",
            wt_session: false,
            top_level_args: NO_TOP_LEVEL_ARGS,
            expected_utf8: "0",
            expected_features: &[],
        },
    ]
}

fn spawn_profile_attach(
    binary: &Path,
    label: &str,
    session: &str,
    profile: TerminalProfile,
) -> Result<SpawnedPty, Box<dyn Error>> {
    let mut command = ChildCommand::new(binary)
        .arg("-L")
        .arg(label)
        .size(TerminalSize::new(100, 30));
    for arg in profile.top_level_args {
        command = command.arg(*arg);
    }
    command = command.args(["attach-session", "-t", session]);
    command = apply_profile_env_to_pty_command(command, profile);
    Ok(command.spawn()?)
}

fn run_control_mode_with_profile(
    binary: &Path,
    label: &str,
    profile: TerminalProfile,
    stdin: &str,
) -> Result<Output, Box<dyn Error>> {
    let mut command = Command::new(binary);
    command.arg("-L").arg(label);
    for arg in profile.top_level_args {
        command.arg(arg);
    }
    command.arg("-C");
    apply_profile_env_to_command(&mut command, profile);
    command.stdin(Stdio::piped());
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());

    let mut child = command.spawn()?;
    child
        .stdin
        .take()
        .expect("control mode stdin is piped")
        .write_all(stdin.as_bytes())?;
    wait_for_child_output(child, CONTROL_TIMEOUT)
}

fn apply_profile_env_to_pty_command(
    command: ChildCommand,
    profile: TerminalProfile,
) -> ChildCommand {
    let command = apply_inherited_env_without_multiplexer_markers(command);

    command
        .env("TERM", profile.term)
        .env("TERM_PROGRAM", profile.term_program)
        .env("COLORTERM", profile.colorterm)
        .env(
            "WT_SESSION",
            if profile.wt_session {
                "rmux-windows-terminal-matrix"
            } else {
                ""
            },
        )
        .env("LC_ALL", "C")
        .env("LC_CTYPE", "")
        .env("LANG", "")
}

fn apply_profile_env_to_command(command: &mut Command, profile: TerminalProfile) {
    command
        .env("TERM", profile.term)
        .env("TERM_PROGRAM", profile.term_program)
        .env("COLORTERM", profile.colorterm)
        .env(
            "WT_SESSION",
            if profile.wt_session {
                "rmux-windows-terminal-matrix"
            } else {
                ""
            },
        )
        .env("LC_ALL", "C")
        .env("LC_CTYPE", "")
        .env("LANG", "")
        .env_remove("RMUX")
        .env_remove("TMUX");
}

fn apply_inherited_env_without_multiplexer_markers(mut command: ChildCommand) -> ChildCommand {
    command = command.clear_env();
    for (name, value) in std::env::vars_os() {
        if is_multiplexer_env_name(&name) {
            continue;
        }
        command = command.env(name, value);
    }
    command
}

fn is_multiplexer_env_name(name: &OsStr) -> bool {
    env_name_eq_ignore_ascii_case(name, "RMUX") || env_name_eq_ignore_ascii_case(name, "TMUX")
}

fn env_name_eq_ignore_ascii_case(name: &OsStr, expected: &str) -> bool {
    name.to_string_lossy().eq_ignore_ascii_case(expected)
}

fn wait_for_attached_client_line(
    binary: &Path,
    label: &str,
    timeout: Duration,
) -> Result<String, Box<dyn Error>> {
    let deadline = Instant::now() + timeout;
    let mut last_stdout = String::new();
    let mut last_stderr = String::new();
    while Instant::now() < deadline {
        let output = run_rmux_output(binary, label, ["list-clients", "-F", FORMAT])?;
        last_stdout = String::from_utf8_lossy(&output.stdout).into_owned();
        last_stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        if output.status.success() {
            if let Some(line) = last_stdout.lines().find(|line| !line.trim().is_empty()) {
                return Ok(line.to_owned());
            }
        }
        thread::sleep(Duration::from_millis(50));
    }

    Err(format!(
        "timed out waiting for attached client; last stdout={last_stdout:?} stderr={last_stderr:?}"
    )
    .into())
}

fn wait_for_pane_pid(
    binary: &Path,
    label: &str,
    session: &str,
    timeout: Duration,
) -> Result<(), Box<dyn Error>> {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        let output = run_rmux_output(
            binary,
            label,
            ["list-panes", "-t", session, "-F", "#{pane_pid}"],
        )?;
        if output.status.success() && !String::from_utf8_lossy(&output.stdout).trim().is_empty() {
            return Ok(());
        }
        thread::sleep(Duration::from_millis(25));
    }
    Err(format!("timed out waiting for a pane pid in session {session}").into())
}

fn extract_control_payload_line(stdout: &[u8]) -> Option<String> {
    String::from_utf8_lossy(stdout)
        .lines()
        .find(|line| !line.starts_with('%') && line.contains('|'))
        .map(ToOwned::to_owned)
}

fn assert_profile_line(
    profile: &TerminalProfile,
    line: &str,
    control_mode: bool,
) -> Result<(), Box<dyn Error>> {
    let parts = line.trim_end().split('|').collect::<Vec<_>>();
    if parts.len() != 4 {
        return Err(format!(
            "profile {} produced malformed list-clients line {line:?}",
            profile.name
        )
        .into());
    }

    assert_eq!(
        parts[0], profile.term,
        "profile {} should preserve client_termname",
        profile.name
    );
    assert_eq!(
        parts[2], profile.expected_utf8,
        "profile {} should preserve client_utf8",
        profile.name
    );

    let features = parts[1].split(',').collect::<Vec<_>>();
    for expected in profile.expected_features {
        assert!(
            features.iter().any(|feature| feature == expected),
            "profile {} should include feature {expected:?}; got {features:?} from {line:?}",
            profile.name
        );
    }

    let flags = parts[3].split(',').collect::<Vec<_>>();
    assert!(
        flags.contains(&"attached") && flags.contains(&"focused"),
        "profile {} should report attached/focused client flags; got {flags:?}",
        profile.name
    );
    if profile.expected_utf8 == "1" {
        assert!(
            flags.contains(&"UTF-8"),
            "profile {} should expose UTF-8 client flag; got {flags:?}",
            profile.name
        );
    } else {
        assert!(
            !flags.contains(&"UTF-8"),
            "profile {} should not expose UTF-8 client flag; got {flags:?}",
            profile.name
        );
    }
    assert_eq!(
        flags.contains(&"control-mode"),
        control_mode,
        "profile {} control-mode flag mismatch in {flags:?}",
        profile.name
    );

    Ok(())
}

struct RmuxServerGuard<'a> {
    binary: &'a Path,
    label: String,
}

impl<'a> RmuxServerGuard<'a> {
    fn new(binary: &'a Path, label: String) -> Self {
        Self { binary, label }
    }
}

impl Drop for RmuxServerGuard<'_> {
    fn drop(&mut self) {
        let _ = Command::new(self.binary)
            .arg("-L")
            .arg(&self.label)
            .arg("kill-server")
            .env_remove("RMUX")
            .env_remove("TMUX")
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

fn run_rmux<const N: usize>(
    binary: &Path,
    label: &str,
    args: [&str; N],
) -> Result<(), Box<dyn Error>> {
    let output = run_rmux_output(binary, label, args)?;
    if !output.status.success() {
        return Err(io::Error::other(format!(
            "rmux command failed with {:?}\nstdout:\n{}\nstderr:\n{}",
            output.status.code(),
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ))
        .into());
    }
    Ok(())
}

fn run_rmux_output<const N: usize>(
    binary: &Path,
    label: &str,
    args: [&str; N],
) -> Result<Output, Box<dyn Error>> {
    Ok(Command::new(binary)
        .arg("-L")
        .arg(label)
        .args(args)
        .env("LC_ALL", "C")
        .env_remove("RMUX")
        .env_remove("TMUX")
        .output()?)
}

fn wait_for_child_output(mut child: Child, timeout: Duration) -> Result<Output, Box<dyn Error>> {
    let deadline = Instant::now() + timeout;
    loop {
        if let Some(_status) = child.try_wait()? {
            return Ok(child.wait_with_output()?);
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let output = child.wait_with_output()?;
            return Err(format!(
                "control-mode client did not exit before timeout; status={:?}\nstdout={}\nstderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            )
            .into());
        }
        thread::sleep(Duration::from_millis(10));
    }
}

fn terminate_spawned(spawned: &mut SpawnedPty) {
    let _ = spawned.child().terminate_forcefully();
    let _ = spawned.child_mut().wait();
}

fn sanitize_label(value: &str) -> String {
    value
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() {
                character
            } else {
                '-'
            }
        })
        .collect()
}

struct MultiplexerEnvGuard {
    _rmux: EnvVarGuard,
    _tmux: EnvVarGuard,
}

impl MultiplexerEnvGuard {
    fn with_fake_outer() -> Self {
        Self {
            _rmux: EnvVarGuard::set("RMUX", INHERITED_RMUX),
            _tmux: EnvVarGuard::set("TMUX", INHERITED_TMUX),
        }
    }
}

struct EnvVarGuard {
    name: &'static str,
    previous_value: Option<OsString>,
}

impl EnvVarGuard {
    fn set(name: &'static str, value: &'static str) -> Self {
        let previous_value = std::env::var_os(name);
        std::env::set_var(name, value);
        Self {
            name,
            previous_value,
        }
    }
}

impl Drop for EnvVarGuard {
    fn drop(&mut self) {
        match self.previous_value.as_ref() {
            Some(value) => std::env::set_var(self.name, value),
            None => std::env::remove_var(self.name),
        }
    }
}